0

我创建了一个带有一个活动的简单应用程序,并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
    }
4

1 回答 1

0

您需要实施BroadcastReceiver. 这里的一个例子:https ://github.com/tutsplus/background-audio-in-android-with-mediasessioncompat/blob/master/app/src/main/java/com/tutsplus/backgroundaudio/BackgroundAudioService.java

于 2019-06-12T21:39:08.240 回答