0
  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?

Ricket
  • 33,368
  • 30
  • 112
  • 143

1 Answers1

0

Use a static WakeLock. Better yet, use my WakefulIntentService, which wraps up this whole pattern.

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491
  • Is there any reason not to just eliminate the Service and implement everything inside my BroadcastReceiver? I think perhaps I've been giving too much weight to the idea of having a Service and perhaps all of this is unnecessary. In fact, I wouldn't even need any wakelocks, since the system establishes a WakeLock for the duration of the onReceive method (inside which I would do everything). – Ricket Jul 23 '10 at 22:58
  • "Is there any reason not to just eliminate the Service and implement everything inside my BroadcastReceiver?" -- if the work to be done is fast (e.g., 50ms), then I'd roll it all into the receiver. Otherwise, you will steal significant CPU time from the foreground process, plus tie up the main application thread for your activity if it happens to be in the foreground. `onReceive()` runs with foreground priority, so if you're doing serious work, you can soak up enough CPU cycles to whack the frame rate of a game the user might be playing at the time. – CommonsWare Jul 24 '10 at 01:07