我正在制作一个应用程序,当我按下多媒体按钮时,它应该执行一些操作。我知道我必须创建一个服务并捕获那里的所有事件。我执行了文档建议的所有操作,但我仍然没有在应用程序中收到单击事件。
我遵循以下准则来编写类似的应用程序:https://developer.android.com/guide/topics/media-apps/mediabuttons
https://developer.android.com/reference/androidx/media/session/MediaButtonReceiver.html
https://code.tutsplus.com/tutorials/create-a-music-player-on-android-song-playback--mobile-22778?_ga=2.241321730.1029380229.1566994251-780734199.1565702660
https://habr.com/ru/post/339416/但我还是没明白这个事件。
我将所有代码放入存储库中:https://gitlab.com/ICaxapI/mediaretranslator/tree/master/app/src/main
以及...以下是我已经遵循的一些建议:
在 AndroidManifest ->
<receiver android:name="androidx.media.session.MediaButtonReceiver">
<intent-filter>
<action android:name="android.intent.action.MEDIA_BUTTON" />
</intent-filter>
</receiver>
...
<service android:name="ru.exsoft.mediaretranslator.RetranslatorService">
<intent-filter>
<action android:name="android.intent.action.MEDIA_BUTTON" />
</intent-filter>
</service>
在服务类中:
override fun onStartCommand(intent: Intent, flags: Int, startId: Int): Int {
MediaButtonReceiver.handleIntent(mediaSession, intent)
return START_STICKY
}
override fun onCreate() {
val stateBuilder: Builder = Builder().setActions(ACTION_PLAY or ACTION_STOP or ACTION_PAUSE or ACTION_PLAY_PAUSE or ACTION_SKIP_TO_NEXT or ACTION_SKIP_TO_PREVIOUS)
...
mediaSession!!.setCallback(mediaSessionCallback)
mediaSession!!.setFlags(MediaSessionCompat.FLAG_HANDLES_MEDIA_BUTTONS or MediaSessionCompat.FLAG_HANDLES_TRANSPORT_CONTROLS)
val state = PlaybackStateCompat.Builder().setActions(
ACTION_PLAY or ACTION_PLAY_PAUSE or
ACTION_PLAY_FROM_MEDIA_ID or ACTION_PAUSE or
ACTION_SKIP_TO_NEXT or ACTION_SKIP_TO_PREVIOUS
).setState(STATE_PLAYING, 5, 1.0f, SystemClock.elapsedRealtime())
.build()
mediaSession?.setPlaybackState(state!!)
mediaSession?.isActive = true
...
val notificationBuilder = NotificationCompat.Builder(this, channelId )
val notification = notificationBuilder.setOngoing(true)
.setSmallIcon(R.mipmap.ic_launcher)
.setPriority(PRIORITY_MAX)
.setCategory(Notification.CATEGORY_SERVICE)
.build()
startForeground(1, notification)
}
以及 GitLab 中的其他内容https://gitlab.com/ICaxapI/mediaretranslator/tree/master/app/src/main
...在 logcat 中,我看到以下几行,确认系统根本没有将我的类视为可以处理此事件的类。 :(
2019-08-29 14:08:44.122 23691-23691/? V/Avrcp_ext: recordKeyDispatched: KeyEvent { action=ACTION_DOWN, keyCode=KEYCODE_MEDIA_PAUSE, scanCode=0, metaState=0, flags=0x0, repeatCount=0, eventTime=508419172, downTime=508419172, deviceId=-1, source=0x0 } dispatched to com.vanced.android.youtube
2019-08-29 14:08:44.122 1675-2510/? D/MediaSessionService: Sending KeyEvent { action=ACTION_UP, keyCode=KEYCODE_MEDIA_PAUSE, scanCode=0, metaState=0, flags=0x0, repeatCount=0, eventTime=508419172, downTime=508419172, deviceId=-1, source=0x0 } to the last known PendingIntent PendingIntent{e2b4330: PendingIntentRecord{7ce4b98 com.vanced.android.youtube broadcastIntent}}