Reliably Pausing Media Playback System-Wide in Android

后端 未结 2 1566
暖寄归人
暖寄归人 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: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);
    

提交回复
热议问题