永不调用MediaSession回调

时间:2019-06-12 17:42:58

标签: android android-mediasession

我创建了一个包含一个活动的简单应用,并通过其MediaSession方法创建了一个onCreate

但是,当我运行该应用程序并使用外部媒体按钮时,永远不会调用该回调。有什么想法可能会丢失吗?

override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        this.mediaSession = MediaSessionCompat(this, "TAG")
        this.mediaSession?.setCallback(object : MediaSessionCompat.Callback() {
            override fun onMediaButtonEvent(mediaButtonIntent: Intent): Boolean {
                return super.onMediaButtonEvent(mediaButtonIntent)
            }
            override fun onPlay() {
                super.onPlay()
            }
        })
        val builder = PlaybackStateCompat.Builder()
        builder.setActions(PlaybackStateCompat.ACTION_PLAY)
        builder.setState(PlaybackStateCompat.STATE_STOPPED, PlaybackStateCompat.PLAYBACK_POSITION_UNKNOWN, 0.0f)
        this.mediaSession?.setPlaybackState(builder.build())
        this.mediaSession?.setFlags(MediaSessionCompat.FLAG_HANDLES_MEDIA_BUTTONS or MediaSessionCompat.FLAG_HANDLES_TRANSPORT_CONTROLS)
        this.mediaSession?.isActive = true
    }