Different instances of Applicationcontext in Broadcastreceiver

I want to access the "global" variable in MyApp (extends the application) from the broadcast broadcaster (registered in the manifest) and, for example, several activities. Now I seem to have different instances of MyApp: one for BCR and one for actions. Can it help me with my problem? thank you very much jorg

+8
android global-variables broadcastreceiver
source share
2 answers

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!

+1
source share

I had a similar problem, I was able to access the object in activity using this template:

public class MyReceiver extends android.content.BroadcastReceiver { private Object _object; public MyReceiver(Someobject) { _object = the object; } @Override public void onReceive(Context context, Intent intent) { Do something to the object. } } 

Then call MyReceiver(theobject) instead of new BroadcastReceiver() .

0
source share

Source: https://habr.com/ru/post/650322/


All Articles