Exoplayer通知无法清除

3

我已经根据此链接在我的应用程序中集成了ExoPlayer。

我在createCurrentContentIntent()中添加了一个待处理的意图(pending intent)。

    return PendingIntent.getActivity(
        context, 0,
        Intent(context, MyActivity::class.java), 0
    )

我遇到了一个问题。我开始播放音频,播放器通知也出现在状态栏中。我的要求是即使应用程序在后台,也要播放音频。因此,我没有在onStop()中释放播放器。我已经在onDestroy()中添加了以下代码。

    override fun onDestroy() {
        playerNotificationManager?.setPlayer(null)
        player?.stop()
        player?.release()
        player = null
        super.onDestroy()
    }

如果我在播放器播放时手动从后台杀死应用程序,则通知不会消失。因此,如果我点击通知,它将由于 MyActivtity 已经不存在而崩溃并显示 NullPointerException。

有人能否就此提供解决方案?


当查看代码时,调用setPlayer(/ * player = * / null)会导致在已经启动通知的情况下取消notificationManager.cancel(notificationId),前提是a)设置了非空播放器并且b)已经开始了通知。所以我很确定它按预期工作。如果您正在运行前台服务中的播放器,并且已调用startForeground(notificationId,notification),则系统不会删除通知,直到您调用stopForeground(/ * removeNotification = * / true || false)。 - Muhammad Ammar
2个回答

0

我已经实现了ExoPlayer,同时使用了MediaSessionCompatMediaSessionConnector,这使得Exo可以隐式地管理媒体通知(以及类似音频焦点的东西)。

class MyServiceClass {

    private lateinit var player: SimpleExoPlayer
    private lateinit var playerNotificationManager: PlayerNotificationManager
    private lateinit var mediaSession: MediaSessionCompat
    private lateinit var mediaSessionConnector: MediaSessionConnector

    override fun onCreate() {
        super.onCreate()

        player = ...
        playerNotificationManager = ...
        mediaSession = MediaSessionCompat(this, CONSTANT).apply{ ..setup callback... }
        mediaSessionConnector = MediaSessionConnector(mediaSession)
        mediaSessionConnector.setPlayer(player)
        playerNotificationManager.setMediaSessionToken(mediaSession.token)
        playerNotificationManager.setPlayer(player)

    }

    override fun onDestroy() {

        mediaSession.isActive = false
        mediaSession.release()
        mediaSessionConnector.setPlayer(null)
        playerNotificationManager.setPlayer(null)
        player.release()

        super.onDestroy()
    }
}

这应该处理在您杀死应用程序时删除通知的操作。

我还使用PlayerNotificationReceiver来对系统通知更改做出反应,但上面的代码中省略了这一部分。此外,整个触发和响应应用程序通知的部分也被省略了。


0

我改变了整个实现过程,使用了服务,这解决了问题。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接