16

Possible Duplicate:
Singletons vs. Application Context in Android?

I don't quite understand this:

When your Application implementation is registered in the manifest, it will be instantiated when your application process is created. As a result your Application implementation is by nature a singleton and should be implemented as such to provide access to its methods and member variables.

public class MyApplication extends Application {
    private static MyApplication singleton;

    // Returns the application instance 
    public static MyApplication getInstance() {
        return singleton;
    }

    public final void onCreate() {
        super.onCreate(); singleton = this;
    }  
}

I was reading that this is recommended... but my Application object MyApp extends Application works just fine... and I don't have such code in it.

I just get the MyApp object by casting getApplication()

so could someone explain the benefits of implementing code like this? and am I missing something obvious?

Community
  • 1
  • 1
ycomp
  • 8,316
  • 19
  • 57
  • 95
  • This is not a duplicate. I wonder if this approach can avoid: https://stackoverflow.com/questions/47834537/android-classcastexception-application-object-is-not-my-custom-application#47834537 – gregm Dec 15 '17 at 15:27

0 Answers0