Reliably Pausing Media Playback System-Wide in Android

后端 未结 2 1587
暖寄归人
暖寄归人 2021-01-03 03:16

The title makes this sound much simpler than it is.. I\'m trying to broadcast an intent that will pause most music players.

I know I can use create a KeyEvent for th

2条回答
  •  萌比男神i
    2021-01-03 03:32

    To pause system wide audio, you don't start an intent but rather request audio focus from the system.

    So when you wish to pause everything do the following (suggested in onCreate):

    //The Variables we'll need to create
    AudioManager am;
    OnAudioFocusChangeListener af;
    
    //I do nothing with this listener, but it's required for the next step.
    af = new OnAudioFocusChangeListener() {
    
          public void onAudioFocusChange(int focusChange) {
              if (focusChange == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK) {
                  // Lower the volume
              } else if (focusChange == AudioManager.AUDIOFOCUS_GAIN) {
                  // Raise it back to normal
              }    
          }
    
    }; 
    
    //Do the actual pause
    am = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
    int request = am.requestAudioFocus(af,
        AudioManager.STREAM_MUSIC,
        AudioManager.AUDIOFOCUS_GAIN);
    

    But don't forget to let go of focus using:

    am.abandonAudioFocus(af);
    

提交回复
热议问题