0

I really like the section on AlarmManager in the CWAC Advanced Android book. I am now worried about my app's work being killed because it doesn't have a wake lock. Here's what I am worried about. Is my worry rational?

See code below. What if doWakefulWork has to start another service? In this case, the other service needs to acuire a WakeLock to keep running, however the is a gap in time between the service starting and onHandleIntent ending where the wakelock could be released!

@Override
final protected void onHandleIntent(Intent intent) {
 try {
  doWakefulWork(intent)
  }
 finally {
   getLock(this).release();
 }
}

My going answer is: doWakefulWork must execute on the same thread, it can't start other threads or services unless the other services are also WakefulIntentService instances.

Am I right?

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491
gregm
  • 12,019
  • 7
  • 56
  • 78
  • Why do you have two services in the first place? – CommonsWare May 04 '11 at 19:19
  • In one case doWakefulWork will launch an activity. If it launches an activity, then is there a need for a wake-lock? In another case, there is some pre-existing code. I could retrofit as you suggest. – gregm May 04 '11 at 19:36
  • If it launches an activity, the device will fall asleep unless the user interacts with the activity first. Since you have no idea if the user is anywhere near the device at the time, I *strongly* encourage you to not try to keep the device awake waiting for a user. I am guessing that consolidating the two services may simplify your life for the long haul, but that's just a guess. – CommonsWare May 05 '11 at 06:52

1 Answers1

1

If you want your other services to hold a WakeLock, then yes they must either be a WakefulIntentService OR acquire the WakeLock by themselves. If you are worried about the time between when you send the intent and when the other service actually acquires the lock you'll need to implement some type of blocking mechanism (ie block the doWakefulWork method from ending until the other service has started and aquired the lock)

smith324
  • 13,020
  • 9
  • 37
  • 58
  • 1
    The block-the-method approach is mildly icky but could work. I'd just implement the wakeful pattern if the other service is not itself a `WakefulIntentService`. The `WakefulIntentService` code is pretty small and largely described in the aforementioned book. – CommonsWare May 04 '11 at 19:19