What I get from this is that you are trying to create a method to create a single Context object. First, for this you will need the Singleton MyApp template to create your "global" variable. However, I would advise against this for these reasons:
- Different components of the application by default have different contexts (base, application).
- The BroadcastReceiver function defined in the manifest is called by the OS, not by your application.
- Using a Singleton pattern for a context object will lead to some very nasty dependencies.
- You go against the design and beauty of the Android Framework.
I would suspect why you are doing this, so your MyApp class can trigger various actions. It makes sense, but ... you can get a context object from almost anywhere. Many things in Android extend the ContextWrapper class (I think Java objects with the Object class). Therefore, there really is no reason to ever have a βglobalβ instance of this. In fact, your BroadcastReceiver onReceive () method accepts a context parameter. You can use this to trigger actions and what not.
If you do not need a singleton MyApp class, and there are justified reasons for using it, I would consider the implementation developed by Bill Pugh , as it is the safest in Java with regard to thread synchronization and blocking.
Hope this helps. Remember, don't fight the SDK, let it work for you!
jjNford
source share