Android 模拟 play/pause 按钮

Android simulating play/pause button

我试图让我的应用程序打开 Google 播放音乐,然后模拟 play/pause 命令。我的应用程序能够成功启动 Google Play Music,但是 downIntentupIntent KeyEvents 永远不会广播。我怀疑这是因为调用该方法只会调用我的主 class 上的方法,而不是播放音乐本身。播放这些 KeyEvents 以播放音乐的正确方法是什么?

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

出于安全原因,您不能。 EXTRA_KEY_EVENT 并没有按照您的想法行事 - 它不会向系统发送关键事件。

我找到了一个非常有帮助的伙伴,他为我指明了正确的方向。

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

这似乎在 Android 4.x 上运行良好,但我尚未在 5.x 上测试过。

如果您想控制音乐播放器(当前正在播放的播放器),可以通过一种方式向其发送 KeyEvents:

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

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

注意:需要minSdk 19以上