Android MediaController Play/Pause button and Seekbar doesn't Refresh

后端 未结 1 675
耶瑟儿~
耶瑟儿~ 2021-02-03 15:28

I am using MediaController.MediaPlayerControl in order to display a MediaController at the bottom of my Custom View but I can\'t get it to work properly. When I play music for f

1条回答
  •  梦谈多话
    2021-02-03 16:15

    I had exactly this problem. Don't know if you still need help, but I thought I'd post anyway. For posterity, are you following this tutorial?

    First, the easy problem: you're getting multiple instances of your controls because of repeated calls to setController(). Change the first line of your function to:

    if (controller == null) controller = new MusicController(this);
    

    With regards to the play button malfunctioning, I believe it's because you're showing it before the music player has been prepared (disclaimer: I'm a newbie to Android myself, and the following are the things I've found to have worked).

    1. Set up a broadcast from your music-playing service to notify your music-controlling activity when the musicplayer has been prepared. Append the following function in your music-playing service to broadcast intent:

      @Override
      public void onPrepared(MusicPlayer player) {
          // Do some other stuff...
      
          // Broadcast intent to activity to let it know the media player has been prepared
          Intent onPreparedIntent = new Intent("MEDIA_PLAYER_PREPARED");
          LocalBroadcastManager.getInstance(this).sendBroadcast(onPreparedIntent);
      }
      
    2. Set up a broadcast receiver in your music-controlling activity to receive the intent broadcast by your service. Add the following class to your activity:

      // Broadcast receiver to determine when music player has been prepared
      private BroadcastReceiver onPrepareReceiver = new BroadcastReceiver() {
      @Override
      public void onReceive(Context c, Intent i) {
          // When music player has been prepared, show controller
          controller.show(0);
          }
      };
      
    3. Register your receiver in your activity's onResume() method:

      // Set up receiver for media player onPrepared broadcast
      LocalBroadcastManager.getInstance(this).registerReceiver(onPrepareReceiver,
              new IntentFilter("MEDIA_PLAYER_PREPARED"));
      
    4. Depending on the structure of your code, you'll have to do some general tidying up. In my code, I've only called setController() twice: from the onCreate() and onResume() methods in my activity. I also only call controller.show(0) from my broadcast receiver, and my onResume() method.

    0 讨论(0)
提交回复
热议问题