开发者

Different Instance of Applicationcontext in Broadcastreceiver

开发者 https://www.devze.com 2023-01-31 07:53 出处:网络
I want to access a \"global\" variable in开发者_Python百科 my MyApp(extends Application) from a broadcastreceiver (registered in the manifest) and e.g. multiple activities. Now I seem to have differen

I want to access a "global" variable in开发者_Python百科 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


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!


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

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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号