我已经在手机上安装了该应用程序,并且在按下耳机上的按钮时会按预期执行回调,但在模拟器上它什么也不做。
使用以下代码生成媒体按钮按下:
adb shell input keyevent 126
有趣的是,我可以使用此命令停止拨出电话。
我什至在 Logcat 的输出中发现了按钮按下日志:
I/Input: injectKeyEvent: KeyEvent { action=ACTION_DOWN, keyCode=KEYCODE_MEDIA_PLAY, scanCode=0, metaState=0, flags=0x0, repeatCount=0, eventTime=46647423, downTime=46647423, deviceId=-1, source=0x101 }
I/Input: injectKeyEvent: KeyEvent { action=ACTION_UP, keyCode=KEYCODE_MEDIA_PLAY, scanCode=0, metaState=0, flags=0x0, repeatCount=0, eventTime=46647423, downTime=46647423, deviceId=-1, source=0x101 }
创建 MediaSession 的代码:
val callback = object : MediaSession.Callback() {
override fun onPlay() = pressCounter.press()
override fun onPause() = pressCounter.press()
override fun onStop() = pressCounter.press()
}
mediaSession = MediaSession(applicationContext, "MYMS")
mediaSession.setCallback(callback)
mediaSession.setPlaybackState(
PlaybackState.Builder().setActions(PlaybackState.ACTION_PLAY or
PlaybackState.ACTION_PAUSE or
PlaybackState.ACTION_PLAY_PAUSE)
.setState(PlaybackState.STATE_PLAYING,
0,
1f).build())
mediaSession.isActive = true