[英]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. 在我的应用程序中,我需要监听ACCESSORY_DETTACHED的意图操作,但是只有在应用程序正在运行时(在前台或后台)才应进行处理,而在应用程序未运行时则不应进行处理。
I know there are 2 options. 我知道有2种选择。 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).
要在Manifest中注册BroadcastReceiver(不会起作用,因为我不希望在我的应用未运行时调用onReceive)或将其注册到Activity中(但是为了避免泄漏,我不得不在某个地方注销它,我不能在onStop中执行此操作,因为我也需要它在后台运行,因此不建议使用onDestroy)。
I figured out I could register receiver in Application class and it works, but still, I cannot unregister it anywhere. 我发现我可以在Application类中注册接收器,并且它可以工作,但是仍然无法在任何地方注销它。 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
. 那将取决于您对自定义
Application
子类和BroadcastReceiver
。
You would not be leaking the receiver by calling registerReceiver()
from the onCreate()
method of your Application
. 通过从
Application
的onCreate()
方法调用registerReceiver()
不会泄漏接收器。 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
. 自定义
Application
其他内容可能会泄漏,具体取决于您在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. 因此,您的方法本身不会是内存泄漏,但是您将需要仔细检查接收器和
Application
,以确保在此过程中不会引入其他泄漏。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.