I have implemented music player which fires a custom notification when stream audio is playing.
Everything is working and I can play/pause the audio using the button
This should work. Just make your notification
and notificationManager
a static global variable.
public class RemoteControlReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if(action.equalsIgnoreCase("com.example.test.ACTION_PLAY")){
if(mediaplayer.isPlaying()){
mediaplayer.pause();
notificationView.setImageViewResource(R.id.button1, R.drawable.play);
notification.contentView = notificationView;
notificationManager.notify(1, notification);
}
else {
mediaplayer.start();
notificationView.setImageViewResource(R.id.button1, R.drawable.pause);
notification.contentView = notificationView;
notificationManager.notify(1, notification);
}
}
}
}
You have to set your notification.contentView to the new remoteView after it was changed so it can update the notification view itself.
Meaning, after you receive the action in your BroadcastReceiver, re-build your notification with the desired button display ( pause or play )
Hope this helps
Hey guys you only need to update "notificationManager.notify(1, notification);" in your onReceiver method after you make changes to same notification. Assign public static to your notification and notificationManager and use in your BroadcastReceiver extended class.
See the below code to know accurately :
public void onReceive(Context context, Intent intent) {
String action1 = intent.getStringExtra("action1");
// String action2 = intent.getStringExtra("action2");
Log.i("Intent Received","Yes");
if(say)
{
if (action1.equals("PauseAction"))
{
performAction1();
say = false;
}
}
else if(!say)
{
if (action1.equals("PauseAction"))
{
performAction2();
say = true;
}
}
public void performAction1()
{
if (mediaPlayer!=null)
{
if(mediaPlayer.isPlaying())
{
playButtonImage.setImageResource(R.drawable.playbutton);
playButtonImage.setContentDescription("Play Button ");
notificationView.setImageViewResource(R.id.remoteViewImageView,R.drawable.playbutton);
mediaPlayer.pause();
play = true;
MainActivity.notificationManager.notify(1, notification);
}
Log.i("performAction1 called ","Yes");
}
}
public void performAction2()
{
if (mediaPlayer != null)
{
mediaPlayer.start();
playButtonImage.setImageResource(R.drawable.pause);
playButtonImage.setContentDescription("Pause Button");
notificationView.setImageViewResource(R.id.remoteViewImageView,R.drawable.pause);
MainActivity.notificationManager.notify(1, notification);
play = false;
Log.i("performAction2 called ", "Yes");
}
}
}
Why not using an ImageView instead of ImageButton? With ImageView, you can simply change its appearance with removeViews.setImageViewResource(R.id.button1, R.drawable.pause);