Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Different Instance of Applicationcontext in Broadcastreceiver

I want to access a "global" variable in my MyApp(extends Application) from a broadcastreceiver (registered in the manifest) and e.g. multiple activities. Now I seem to have different instances of my MyApp: one for the BCR and one for the activities. Could sb help me with my problem? thanks alot Joerg

like image 281
Joerg Kaiser Avatar asked Dec 21 '10 00:12

Joerg Kaiser


Video Answer


1 Answers

What I get from this is that you are trying to create a method to having a single Context object. First off, to do this you would need a Singleton Pattern of MyApp to create your "global" variable. However I would advice against this for these reasons:

  1. Different application components by default have different contexts (base, application).
  2. A BroadcastReceiver defined in the manifest is invoked by the OS, not by your application.
  3. Using a Singleton Pattern for a context object will lead to some very nasty dependencies.
  4. You are going against the design and beauty of the Android Framework.

I would suspect the reason you are doing this is so your MyApp class can start different activities. This makes sense, but... you can get a Context Object from almost anywhere. Many things in Android extend the ContextWrapper class (think Java Objects with the Object class). So there is really no reason to ever have a "global" instance of this. In fact your BroadcastReceiver's onReceive() method accepts a context parameter. You can use this to start activities and what not.

If this is not why you are wanting the MyApp singleton class - and there are justifiable reasons for needing it, I would look at the implementation designed by Bill Pugh as it is the safest in Java taking into account thread synchronization and locking.

Hope this helps. Remember, don't fight the SDK, let it work for you!

like image 92
jjNford Avatar answered Sep 20 '22 00:09

jjNford