raphnguyen raphnguyen - 5 months ago 56
Android Question

Android simulating play/pause button

I'm trying to make my application open up Google Play Music and then simulate a play/pause command. My application is able to start Google Play Music successfully, but the

KeyEvents are never broadcast. I suspect this is because calling the method just invokes the method on my main class and not Play Music itself. What's the proper way to broadcast these KeyEvents to Play Music?

Intent intent = getPackageManager().getLaunchIntentForPackage("com.google.android.music");

Intent downIntent = new Intent(Intent.ACTION_MEDIA_BUTTON, null);
KeyEvent downEvent = new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE);
downIntent.putExtra(Intent.EXTRA_KEY_EVENT, downEvent);
sendOrderedBroadcast(downIntent, null);

Intent upIntent = new Intent(Intent.ACTION_MEDIA_BUTTON, null);
KeyEvent upEvent = new KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE);
upIntent.putExtra(Intent.EXTRA_KEY_EVENT, upEvent);
sendOrderedBroadcast(upIntent, null);


I found a very helpful buddy who pointed me in the right direction.

Intent intent = new Intent("com.android.music.musicservicecommand");
intent.putExtra("command", "togglepause");

This seems to work well on Android 4.x, but I have not tested it on 5.x.