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
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).
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);
}
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);
}
};
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"));
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.