简体   繁体   English

Android BroadcastReceiver等待服务启动还是将WakeLock传输到Service?

[英]Android BroadcastReceiver wait for Service to start or transmit WakeLock to Service?

  1. BroadcastReceiver receives a broadcast, opens a wakelock, starts a Service BroadcastReceiver接收广播,打开唤醒锁,启动服务
  2. Service opens another wakelock, then sends a "release wakelock" broadcast 服务打开另一个唤醒锁,然后发送“释放唤醒锁”广播
  3. BroadcastReceiver receives the release wakelock broadcast and releases its wakelock BroadcastReceiver接收释放唤醒锁广播并释放其唤醒锁
  4. Service does its thing and releases its wakelock 服务完成其事并释放其唤醒锁

There's a problem though. 不过有一个问题。 Currently the BroadcastReceiver stores its WakeLock as a member variable. 当前,BroadcastReceiver将其WakeLock存储为成员变量。 Sometimes the garbage collector will run after the BroadcastReceiver starts the service but before it receives the release wakelock broadcast, and then I get a force close because the wakelock is finalized before it is released (since it gets garbage collected). 有时,垃圾收集器将在BroadcastReceiver启动服务之后但在接收到释放的唤醒锁广播之前运行,然后我被强制关闭,因为唤醒锁在释放之前已完成(因为它已被垃圾收集)。

So I need to, in the onReceive method, do one of the following: 因此,我需要在onReceive方法中执行以下一项操作:

  • wait for the service to start, wait for it to establish its wakelock, and then release the BroadcastReceiver wakelock; 等待服务启动,等待其建立唤醒锁,然后释放BroadcastReceiver唤醒锁; the 'release wakelock' broadcast will no longer be necessary 不再需要“释放唤醒锁”广播
  • or, somehow transmit the wakelock to the service, and then the service will be responsible for releasing the single wakelock 或以某种方式将唤醒锁传输到服务,然后服务将负责释放单个唤醒锁

Which one is the better option and how would I accomplish it? 哪个是更好的选择,我将如何实现?

Use a static WakeLock . 使用静态WakeLock Better yet, use my WakefulIntentService , which wraps up this whole pattern. 更好的是,使用我的WakefulIntentService ,它包装了整个模式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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