Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: will the dynamically registered broadcast receiver be activated if the app process has been killed

Tags:

android

As I know, statically registered (via manifest) broadcast receiver will be activated when the broadcast is fired, it doesn't require the app process is running. But what about the dynamically registered one?

like image 865
Dagang Avatar asked Feb 15 '23 07:02

Dagang


2 Answers

AFAIK, You can make your Broadcast Receiver can run in background even your application is closed or destroyed or killed.

If you want to do above one , you should not be registering it via registerReceiver(). Register it in the manifest via a element instead. Then, it is available whether or not your application is running.

One more option if you want the broadcast receiver to killed or stopped whenever your application is closed or destroyed or killed.

you should call/invoke registerReceiver() method in your onCreate and You should call/invoke unregisterReceiver() in onResume() or in onpause() methods as per your need you can use this.

like image 114
Sankar Ganesh PMP Avatar answered May 08 '23 22:05

Sankar Ganesh PMP


One of the differences between BroadcastReceiver that declared in AndroidManifest.xml and the one that registered with Context.registerReceiver() is that first one is instantiated by the Android system, when the second one - by the application code. When application process is terminated, all it's data (including all objects and jvm itself) is destroyed. So the only way to handle broadcast Intent for your receiver is to start new application process, instantiate new YourBroadcastReceiver and call its onReceive() method (and this is what it does for receivers, declared in manifest). But in case of receiver that was dynamically registered with registerReceiver() the system gets just some receiver instance, but not a mechanism for its creation. Furthermore, if for example your receiver class is non-static inner class then there is no reasonable way to instantiate it by the external (system) code because the system could not know, in which state the external object (and application) should be, to receiver worked properly. Also constructor could have arguments.

So if the process is terminated, your dynamically registered BroadcastReceiver will never called until you register new one in a new process.

like image 38
praetorian droid Avatar answered May 08 '23 22:05

praetorian droid