Control the default music player of android or any other music player

后端 未结 7 1085
抹茶落季
抹茶落季 2020-11-28 06:05

How to control the default music player of android or any other player? By controlling i mean pause, play, next etc. Do i have to bind the service? I have tried to use the <

7条回答
  •  天涯浪人
    2020-11-28 06:54

    KeyEvent's don't work properly in newest Android, as well as don't support applications like Spotify. The best solution is to use MediaController. For each application that is currently playing and you want to control it you have to create different MediaController. It requires Context and MediaSession.Token. Token 'identifies' process that plays music. For example if you played Google Play Music and you now play Spotify you can create MediaControllers for both. How to retrieve tokens? There are two ways:

    • Get list from MediaSessionManager. You can find it in Google example project
    • Get it from Notifications - if you have access to Notifications (NotificationListenerService) you can search for notifications from music apps and get their current Token.

    You check current state of session from MediaController:

    getPlaybackState().getState() //e.g. PlaybackStateCompat.STATE_PLAYING
    

    and control app using transport controls, e.g.:

    getTransportControls().skipToNext()
    

    Depending on your minSDK use Compat or not version. You can cast MediaSession.Token to MediaSessionCompat.Token with:

    MediaSessionCompat.Token.fromToken(token)
    

提交回复
热议问题