MediaButtonReceiver не работает с MediaSession - PullRequest
0 голосов
/ 25 февраля 2020

Я пытаюсь получить события мультимедийных кнопок от проводных / Bluetooth-гарнитур

Я получаю события мультимедийных кнопок в методе onMediaButtonEvent (mediaButtonEvent: Intent?) В MediaSessionCallback, но с музыкой ничего не происходит c воспроизведение.

Вот мой MediaPlayerService

private const val LOG_TAG = "LOG_TAG"
private const val MY_EMPTY_MEDIA_ROOT_ID = "empty_root_id"
private const val AUDIO_URL_1 = "https://www.listennotes.com/e/p/94051189e660408b861be9ee28f17f06/"

class MediaPlaybackService : MediaBrowserServiceCompat() {

    private val TAG = "MediaPlaybackService"
    private lateinit var context: Context
    private lateinit var mediaSession: MediaSessionCompat
    private lateinit var stateBuilder: PlaybackStateCompat.Builder
    private lateinit var exoPlayer: SimpleExoPlayer
    private lateinit var dataSourceFactory: DefaultDataSourceFactory
    private val audioAttributes = AudioAttributes.Builder()
        .setContentType(C.CONTENT_TYPE_MUSIC)
        .setUsage(C.USAGE_MEDIA)
        .build()

    override fun onCreate() {
        super.onCreate()
        context = this
        initExoPlayer()
        initDataSourceFactory()
        initMediaSession()
    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        Log.i(TAG, "onStartCommand ${intent?.getParcelableExtra<KeyEvent>                         
                  (Intent.EXTRA_KEY_EVENT)?.keyCode}")
        MediaButtonReceiver.handleIntent(mediaSession, intent)
        return super.onStartCommand(intent, flags, startId)
    }

    private fun initExoPlayer() {
        exoPlayer = ExoPlayerFactory.newSimpleInstance(context)
        exoPlayer.setAudioAttributes(audioAttributes, true)
    }

    private fun initDataSourceFactory() {
        val httpDataSourceFactory = DefaultHttpDataSourceFactory(
            Util.getUserAgent(context, "media-player"),
            null,
            DefaultHttpDataSource.DEFAULT_CONNECT_TIMEOUT_MILLIS,
            DefaultHttpDataSource.DEFAULT_READ_TIMEOUT_MILLIS,
            true
        )
        dataSourceFactory = DefaultDataSourceFactory(context, null, httpDataSourceFactory)
    }

    private fun initMediaSession() {
        mediaSession = MediaSessionCompat(context, LOG_TAG).apply {
            setFlags(
                MediaSessionCompat.FLAG_HANDLES_MEDIA_BUTTONS
                    or MediaSessionCompat.FLAG_HANDLES_TRANSPORT_CONTROLS
            )
            stateBuilder = PlaybackStateCompat.Builder()
                .setActions(
                    PlaybackStateCompat.ACTION_PLAY_PAUSE
                        or PlaybackStateCompat.ACTION_PLAY
                        or PlaybackStateCompat.ACTION_PAUSE
                        or PlaybackStateCompat.ACTION_SKIP_TO_NEXT
                        or PlaybackStateCompat.ACTION_SKIP_TO_PREVIOUS
                )
            setPlaybackState(stateBuilder.build())
            setCallback(mediaSessionCallback())
            setSessionToken(sessionToken)
            isActive = true
        }
    }

        private fun mediaSessionCallback() = object : MediaSessionCompat.Callback() {
        override fun onPlay() {
            super.onPlay()
            play()
        }

        override fun onPause() {
            super.onPause()
            pause()
        }

        override fun onSkipToNext() {
            super.onSkipToNext()
            skipToNext()
        }

        override fun onSkipToPrevious() {
            super.onSkipToPrevious()
            skipToPrevious()
        }

        override fun onMediaButtonEvent(mediaButtonEvent: Intent?): Boolean {
            Log.i(TAG, "MediaButtonEvent: ${mediaButtonEvent?.getParcelableExtra<KeyEvent> 
                  (Intent.EXTRA_KEY_EVENT)?.keyCode}")
            return super.onMediaButtonEvent(mediaButtonEvent)
        }
    }

    fun play() {
        Log.i(TAG, "Playback State: Playing")
        if (mediaSession.controller.playbackState.state != PlaybackStateCompat.STATE_PAUSED) {
            val mediaSource = getMediaSource(AUDIO_URL_1)
            exoPlayer.prepare(mediaSource)
        }
        setPlaybackState(PlaybackStateCompat.STATE_PLAYING)
        exoPlayer.playWhenReady = true
        setMediaMetadata(title = "Episode 131: Bourne Wild")
    }

    fun pause() {
        Log.i(TAG, "Playback State: Paused")
        setPlaybackState(PlaybackStateCompat.STATE_PAUSED)
        exoPlayer.playWhenReady = false
    }

    fun skipToNext() {
        if (exoPlayer.hasNext()) {
            Log.i(TAG, "ExoPLayer: Skip to Next")
            exoPlayer.next()
        }
    }

    fun skipToPrevious() {
        if (exoPlayer.hasPrevious()) {
            Log.i(TAG, "ExoPLayer: Skip to Previous")
            exoPlayer.previous()
        }
    }
    override fun onLoadChildren(parentId: String, result:     
         Result<MutableList<MediaBrowserCompat.MediaItem>>) {
         result.sendResult(null)
     }

     override fun onGetRoot(lientPackageName: String, clientUid: Int,      
              rootHints: Bundle?): BrowserRoot? {
         return BrowserRoot(MY_EMPTY_MEDIA_ROOT_ID, null)
     }

     override fun onDestroy() {
         exoPlayer.release()
         mediaSession.run {
             isActive = false
             release()
          }
         super.onDestroy()
     }
}

Вот мой манифест

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.media_player">

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.FOREGROUND_SERVICE" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:usesCleartextTraffic="true"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <action android:name="android.intent.action.VIEW" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <service android:name=".MediaPlaybackService">
            <intent-filter>
                <action android:name="android.intent.action.MEDIA_BUTTON" />
            </intent-filter>
        </service>

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

</manifest>

Похоже, я Я что-то упустил, после многих дней борьбы, я не мог найти, что не так. Любая помощь будет очень признателен Спасибо

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...