Reliably Pausing Media Playback System-Wide in Android

后端 未结 2 1568
暖寄归人
暖寄归人 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条回答
  • 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);
    
    0 讨论(0)
  • 2021-01-03 03:41

    I ran across this as well. Thanks to your description of it, I think i understand what's going on. You send the keydown event, but never the keyup so to the system thinks the play/pause button is being continuously pressed. I used this piece of code successfully.

    Intent mediaEvent = new Intent(Intent.ACTION_MEDIA_BUTTON);
    KeyEvent event = new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_MEDIA_PLAY); 
    mediaEvent.putExtra(Intent.EXTRA_KEY_EVENT, event);
    context.sendBroadcast(mediaEvent);
    
    new Timer().schedule(new TimerTask() {
        @Override
        public void run() {
            Intent mediaEvent = new Intent(Intent.ACTION_MEDIA_BUTTON);
            KeyEvent event = new KeyEvent(KeyEvent.ACTION_UP,KeyEvent.KEYCODE_MEDIA_PLAY); 
            mediaEvent.putExtra(Intent.EXTRA_KEY_EVENT, event);
            context.sendBroadcast(mediaEvent);
        }
    }, 100);
    
    0 讨论(0)
提交回复
热议问题