简体   繁体   中英

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, eg 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">
   <intent-filter>
      <action android:name="android.media.AUDIO_BECOMING_NOISY" />
   </intent-filter>
</receiver>

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 {
       @Override
       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)
          }
       }
    }

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