Android - get a reference to a BroadcastReceiver defined in Manifest

£可爱£侵袭症+ 提交于 2019-12-01 20:26:01

When registering a BroadcastReceiver in the manifest, you're registering the class, not an instance of it. Each time a broadcast occurs that your <receiver> needs handle, a new instance is created to do so, so you can't really get a reference to one as you're describing.

It's perfectly fine to dynamically instantiate and register an instance of a Receiver class that you've also statically registered in the manifest. I would note, though, that if the statically registered class is going to be run anyway - that is, if it's going to handle the same broadcasts as the dynamically registered one - you might consider just notifying your Activity from the Receiver class - e.g., with LocalBroadcastManager, another event bus implementation, etc. - instead of essentially duplicating Receivers.

There's no need to 'obtain a reference' to BroadcastReceiver which is already registered.

Just send Intent which can be handled by that BroadcastReceiver to trigger its action from any point of the code where you have a Context.

context.sendBroadcast(intent);

If you want to call 'pure logic' without calling BroadcastReceiver you have to extract logic from it to some POJO class and call that class directly omitting BroadcastReceiver.

class LocationReceiver extends BroadcastReceiver {

       private SomeAction action;

       public LocationReceiver(){
           action = new SomeAction();
       }

        @Override
        public void onReceive(Context context, Intent intent) {
            action.execute();
        }
    };

BroadcastReceiver can simply call execute() but it doesn't know anything about how it works. You can reuse SomeAction anywhere in your code without having a knowledge about BroadcastReceiver at all.

Try to avoid putting a logic inside Android classes.

It's better to have logic in POJO Java classes because it helps to keep SRP principle alive and makes testing easier.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!