Reputation: 1819
I am trying to control universal music playback (play/pause, skip etc.) by emulating headset music controls. Is there a way to broadcast the ACTION_MEDIA_BUTTON intent? I tried the regular way with sendBroadcast() but it didn't work.
Is this possible?
Upvotes: 4
Views: 3539
Reputation: 46
You can dispatch different KeyEvent.KEYCODE_MEDIA_* to AudioManager
AudioManager audio = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
audio.dispatchMediaKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN,
KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE));
audio.dispatchMediaKeyEvent(new KeyEvent(KeyEvent.ACTION_UP,
KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE));
This will only work for apps that listen to these media events by calling
AudioManager.registerMediaButtonEventReceiver or MediaSession.setMediaButtonReceiver
Upvotes: 2
Reputation: 4725
Try this
long eventtime = SystemClock.uptimeMillis();
Intent downIntent = new Intent(Intent.ACTION_MEDIA_BUTTON, null);
KeyEvent downEvent = new KeyEvent(eventtime, eventtime,
KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE, 0);
downIntent.putExtra(Intent.EXTRA_KEY_EVENT, downEvent);
sendOrderedBroadcast(downIntent, null);
Intent upIntent = new Intent(Intent.ACTION_MEDIA_BUTTON, null);
KeyEvent upEvent = new KeyEvent(eventtime, eventtime,
KeyEvent.ACTION_UP, KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE, 0);
upIntent.putExtra(Intent.EXTRA_KEY_EVENT, upEvent);
sendOrderedBroadcast(upIntent, null);
Upvotes: 4