简体   繁体   中英

Android BroadcastReceiver wait for Service to start or transmit WakeLock to Service?

  1. BroadcastReceiver receives a broadcast, opens a wakelock, starts a Service
  2. Service opens another wakelock, then sends a "release wakelock" broadcast
  3. BroadcastReceiver receives the release wakelock broadcast and releases its wakelock
  4. Service does its thing and releases its wakelock

There's a problem though. Currently the BroadcastReceiver stores its WakeLock as a member variable. 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).

So I need to, in the onReceive method, do one of the following:

  • wait for the service to start, wait for it to establish its wakelock, and then release the BroadcastReceiver wakelock; 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 . Better yet, use my WakefulIntentService , which wraps up this whole pattern.

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