Using WakeLock to Keep A Stream Playing

yydl picture yydl · Jun 22, 2011 · Viewed 11.6k times · Source

I have a MediaPlayer running in a Service that's playing audio from a URL (streaming). As of now it appears to work well, and even continues playing when I put the phone in standby.

I currently do not acquire a wakelock. My question is:

  • Is it actually necessary to acquire a wakelock in my situation?
  • If it is necessary, what type of wakelock should I acquire?

And yes, this is a legitimate use-case for wakelock, because my users explicitly want the audio to continue playing.

Answer

Dylan Knowles picture Dylan Knowles · Jun 27, 2011
  1. Watch the phone for about five minutes when it is on standby. If it continues playing, you do not need a wake lock; it probably indicates that the MediaPlayer instance already has one. In Android, after about two minutes of inactivity from the user anything non-essential which is without a wakelock will be suspended; five minutes should remove any doubt surrounding the two minute timer.
  2. Try a partial wake lock. It'll let your users hear the audio as the processor will be kept "awake." However, it won't waste battery on displaying an image as the screen is allowed to go to sleep. This is probably what you want.

EDIT: If you want to play on the safe side then you want to use a WakeLock. That way if MediaPlayer ever changes and is allowed to go to sleep when the phone suspends your program will still work correctly. There really is nothing to lose by adding the WakeLock providing that you corretly release it when it is no longer required. If you do not you will simply drain more battery than you intend to and, in the worst case, you will immediately see an error indicating that you did not release the lock when your application terminates. Adding a WakeLock - while potentially redundant - is a good practice as it makes your applicaiton more robust against changes to the software that it depends upon.