简体   繁体   中英

Unregistering a BroadcastReceiver from a non-Activity on Android

I have an Android library that requires a BroadcastReceiver, which I register in an object constructor. It performs actions on that object based on changing internet state. But, I'm encountering error messages about a leaked receiver, because I don't call unregister.

How and where can I call unregister when I have no information on when the Activity would end? Since I am only providing the class that would be instantiated by an Activity, so no onPause, onClose methods.

You could try saving your receiver in a static. I think only get this error if you register the same receiver twice.

If that fails, you might also try calling context.getApplicationContext().registerBroadcastReceiver() instead of using the activity context.

Shouldn't you be extending Activity , working properly with Android's workflow, and then have your users extend your Activity?

It's just a suggestion, but it would definitely solve the problem you're describing since you could register the receiver on onCreate() and unregister it on onDestroy() .

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