【问题标题】:Android MediaSessionCompat Callbacks not firingAndroid MediaSessionCompat 回调未触发
【发布时间】:2021-01-20 11:50:42
【问题描述】:

我正在创建一个有声读物播放器,并且正在使用 MediaSessionCompat 相关的类来处理通知。我的代码深受 android-MediaBrowserService 示例 (https://github.com/googlearchive/android-MediaBrowserService) 的启发,我目前还不太了解它(尤其是 createContentIntent)

这是我的简单类,负责从提供元数据和播放状态数据的 bookPlayer 构建通知

class PlayerNotificationManager(val playerService: PlayerService) {

    val CHANNEL_ID = "pylvain.gamma"
    val NOTIFICATION_ID = 412
    private val REQUEST_CODE = 501

    val notificationManager =
        playerService.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager

    private val playAction: NotificationCompat.Action =
        NotificationCompat.Action (
            android.R.drawable.ic_media_pause,
            "PAUSE",
            buildMediaButtonPendingIntent(
                playerService,
                PlaybackStateCompat.ACTION_PAUSE
            )
        )

    fun getNotification(bookPlayer: BookPlayer): Notification  {

        if (isAndroidOOrHigher()) createChannel()

        val style = androidx.media.app.NotificationCompat.MediaStyle()
            .setMediaSession(playerService.sessionToken)
            .setShowCancelButton(true)
            .setShowActionsInCompactView(0)
            .setCancelButtonIntent(
                buildMediaButtonPendingIntent(
                    playerService,
                    PlaybackStateCompat.ACTION_STOP
                )
            )

        val builder = NotificationCompat.Builder(playerService, CHANNEL_ID)
            .addAction(playAction)
            .setStyle(style)
            .setSmallIcon(R.drawable.ic_music_rest_quarter)
            .setContentIntent(createContentIntent())
            .setVisibility(NotificationCompat.VISIBILITY_PUBLIC)

        return builder.build()

    }

    private fun createContentIntent(): PendingIntent { //TODO: Understand that
        Timber.i("Creating Intent")
        val openUI = Intent(playerService, MainActivity::class.java)
        openUI.flags = Intent.FLAG_ACTIVITY_SINGLE_TOP
        return PendingIntent.getActivity(
            playerService, 0, openUI, PendingIntent.FLAG_UPDATE_CURRENT
        )
    }

通知与元数据显示完美

这是我的 MediaBrowserService 处理媒体会话,我在其中注册了回调。 bookplayer 是用 Koin 构建和注入的。 :

class PlayerService : MediaBrowserServiceCompat() {

    private lateinit var playerNotificationManager: PlayerNotificationManager
    lateinit var session: MediaSessionCompat

    private val bookPlayer: BookPlayer by inject()

    override fun onCreate() {
        super.onCreate()

        session = MediaSessionCompat(this, "MusicService")
        session.apply {
            setFlags(
                MediaSessionCompat.FLAG_HANDLES_MEDIA_BUTTONS or
                        MediaSessionCompat.FLAG_HANDLES_TRANSPORT_CONTROLS
            )
            setPlaybackState(bookPlayer.playbackState)
            setMetadata(bookPlayer.getMetadata())
            setCallback(callbacks)
            setActive(true)
        }

        setSessionToken(session.sessionToken)
        playerNotificationManager = PlayerNotificationManager(this)

        val notification = playerNotificationManager.getNotification(bookPlayer)

        startForeground(playerNotificationManager.NOTIFICATION_ID, notification)

    }

    override fun onTaskRemoved(rootIntent: Intent?) { //TODO
        super.onTaskRemoved(rootIntent)
        stopSelf()
    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        return super.onStartCommand(intent, flags, startId)
    }

    override fun onGetRoot(
        clientPackageName: String,
        clientUid: Int,
        rootHints: Bundle?
    ): BrowserRoot? {
        return BrowserRoot("root", null)
    }

    override fun onLoadChildren(
        parentId: String, result: Result<MutableList<MediaBrowserCompat.MediaItem>>
    ) {
        result.sendResult(null);
    }
    
    override fun onDestroy() {
        session.release()
    }


    val callbacks = object : MediaSessionCompat.Callback() {

        override fun onCommand(command: String?, extras: Bundle?, cb: ResultReceiver?) {
            Timber.i("Test")
            super.onCommand(command, extras, cb)
        }

        override fun onPrepare() {
            Timber.i("Preparing")
        }

        override fun onPlay() {
            Timber.i("Playing")
            bookPlayer.pause()
        }

        override fun onPause() {
            Timber.i("Pausing")
            bookPlayer.pause()
        }

        override fun onSkipToNext() {}
        override fun onSkipToPrevious() {}
        override fun onStop() {}
        override fun onSeekTo(pos: Long) {}
        override fun onMediaButtonEvent(mediaButtonIntent: Intent): Boolean = true

    }

}

然后从主Activity启动服务

startService(Intent(mainContext, PlayerService::class.java))

我也将此添加到我的 Android 清单中


        <service android:name=".playerservice.PlayerService">
            <intent-filter>
                <action android:name="android.media.browse.MediaBrowserService" />
            </intent-filter>
        </service>


        <receiver android:name="androidx.media.session.MediaButtonReceiver">
            <intent-filter>
                <action android:name="android.intent.action.MEDIA_BUTTON" />
            </intent-filter>
        </receiver>

每当我按下按钮时,都不会调用任何回调。当我这样做时,应用程序会记录以下文本:

D/MediaBrowserCompat: Connecting to a MediaBrowserService.

然后什么都没有发生... 我搜索了整个互联网,我完全一无所知,但这肯定很简单。有人能帮我吗 ?非常感谢您提前

【问题讨论】:

    标签: android kotlin service mediasession


    【解决方案1】:

    回调起作用了……只是不符合预期。原来是播放动作按钮在调用

    override fun onMediaButtonEvent(mediaButtonIntent: Intent): Boolean = true
    

    我删除了这个函数,然后……它工作了……

    感谢您的关注!

    【讨论】:

    • documentation for handling media buttons 实际上专门调用了“Android 通过调用 onMediaButtonEvent() 自动将媒体按钮事件分派到您的活动媒体会话。默认情况下,此回调将 KeyEvent 转换为适当的媒体会话回调匹配关键代码的方法。" - 你删除了默认实现,所以是的,你不会得到默认行为。
    • 对不起,我有点咸。我花了几个小时才找到那个错误。不容易发现
    【解决方案2】:

    如果你想获得媒体按钮,你必须播放一些东西。 尝试在您的服务启动时播放虚拟音频

        // play dummy audio
        AudioTrack at = new AudioTrack(AudioManager.STREAM_MUSIC, 48000, AudioFormat.CHANNEL_OUT_STEREO, AudioFormat.ENCODING_PCM_16BIT,
                AudioTrack.getMinBufferSize(48000, AudioFormat.CHANNEL_OUT_STEREO, AudioFormat.ENCODING_PCM_16BIT), AudioTrack.MODE_STREAM);
        at.play();
    
        // a little sleep 
        at.stop();
        at.release();
    

    https://stackoverflow.com/a/50678833/9891730 - 这是我之前的回答

    【讨论】:

      猜你喜欢
      • 2016-11-04
      • 2021-05-24
      • 1970-01-01
      • 2011-02-12
      • 2020-08-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多