4

我正在尝试通过模拟耳机音乐控件来控制通用音乐播放(播放/暂停、跳过等)。有没有办法广播 ACTION_MEDIA_BUTTON 意图?我尝试了使用 sendBroadcast() 的常规方式,但没有成功。

这可能吗?

4

2 回答 2

3

尝试这个

  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); 
于 2012-10-17T04:33:11.877 回答
1

您可以向 AudioManager 发送不同的 KeyEvent.KEYCODE_MEDIA_*

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

这仅适用于通过调用监听这些媒体事件的应用程序

AudioManager.registerMediaButtonEventReceiver or MediaSession.setMediaButtonReceiver
于 2020-09-23T19:48:21.440 回答