简体   繁体   中英

Android Broadcast Receiver when app is running in background

There have beed many questions similar to this but none of them adresses my problem (please, read whole question).

In my application I need to listen for ACCESSORY_DETTACHED intent action, but it should be handled only when app is running (in foreground or background) and NOT when app is not running.

I know there are 2 options. To register BroadcastReceiver in Manifest (won't work as I don't want onReceive to be called when my app is not running) or to register it in Activity (but then I'd have to unregister it somewhere to avoid leaks and I cannot do this in onStop as I need it to work in background as well and onDestroy is not recommended).

I figured out I could register receiver in Application class and it works, but still, I cannot unregister it anywhere. Does this approach lead to leaks? Should I even bother? Are there any other possibilities?

Does this approach lead to leaks?

That would depend upon your implementation of the custom Application subclass and the BroadcastReceiver .

You would not be leaking the receiver by calling registerReceiver() from the onCreate() method of your Application . We reserve the term "leak" for using memory when we do not want to, and you want the receiver to be working as long as your process is alive.

However, the receiver might leak memory, depending on what it holds onto (if anything), as it will be around as long as your process is. Other stuff in your custom Application might be leaked, depending on what else you are doing in the Application .

So, your approach will not itself be a memory leak, but you will want to check your receiver and Application closely to make sure that you are not introducing other leaks along the way.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM