简体   繁体   中英

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 downIntent and upIntent 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");
startActivity(intent);

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);

If you want to control the music player (the current playing one) there is a way to send KeyEvents to it:

if (mAudioManager == null) mAudioManager = (AudioManager)getSystemService(AUDIO_SERVICE);

KeyEvent event = new KeyEvent(KeyEvent.ACTION_DOWN, keyCode); mAudioManager.dispatchMediaKeyEvent(event);

Note: it needs to have minSdk 19 or more.

You can't, for security reasons. EXTRA_KEY_EVENT doesn't do what you think it does- it does not send key events to the system.

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");
sendBroadcast(intent);

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM