James Krawczyk James Krawczyk - 4 months ago 8x
Android Question

Release WAKELOCK when screen is off

I'm making an Android TV and Amazon Fire TV app that uses WAKELOCK to prevent the TV device from going to sleep. What I need to do though is release the WAKELOCK when the screen gets turned off, e.g. when someone presses the power button on the TV, as in this case the Amazon Fire TV Stick etc stay active although the TV is powered off.

I then need to re-add the WAKELOCK when the TV is powered on. What is the accepted best practice for handling this?


EDIT: as per comment I'm updating this response with the most effective method.

In a nutshell you can achieve this in two ways:

  1. Check if the HDMI gets disconnected (mainly works on phones, keep reading for TV)
  2. Check if the audio channel becomes noisy. As per Android documentation (https://developer.android.com/guide/topics/media/mediaplayer.html#noisyintent) you can do something like the following (change with ):

"You can ensure your app stops playing music in these situations by handling the ACTION_AUDIO_BECOMING_NOISY intent, for which you can register a receiver by adding the following to your manifest:

    <receiver android:name=".MusicIntentReceiver">
      <action android:name="android.media.AUDIO_BECOMING_NOISY" />

This registers the MusicIntentReceiver class as a broadcast receiver for that intent. You should then implement this class:

public class MusicIntentReceiver extends android.content.BroadcastReceiver {
       public void onReceive(Context ctx, Intent intent) {
          if (intent.getAction().equals(
                        android.media.AudioManager.ACTION_AUDIO_BECOMING_NOISY)) {
              // signal your service to stop playback
              // (via an Intent, for instance)