简体   繁体   中英

RemoteView does not change image

I have a service that displays a notification when it starts. The notification looks like MediaPlayer controls. When the pause button is clicked, the Service is called again and the media player pauses. On clicking again, it resumes playing. However, the images do not toggle. Here is my code:

@Override
public int onStartCommand(Intent intent, int flags, int startId){
    MediaPlayer player = PodcastrApplication.newInstance().getMediaPlayer();
    request = intent.getIntExtra(REQUEST_CODE, 0);
    if(request == PAUSE){
        // Toggle Play and Pause
        if(player.isPlaying()){
            player.pause();
            rm.setImageViewResource(R.id.pause, R.drawable.ic_action_play);
        }else{
            player.start();
            rm.setImageViewResource(R.id.pause, R.drawable.ic_action_pause);
        }
    }else if(request == DISMISS){
        hideNotification();
        stopSelf();
    }

    return START_STICKY;
}  

Why does it not work?

I thought it was a thread issue so I even tried using a Handler but that did not work either.
Another hack is to cancel the notification and display a new one all together which seems pretty expensive to do.

So, a little change. I added a new method:

 private void updateNotification(){
        NotificationManager mgr = (NotificationManager) getApplicationContext()
                  .getSystemService(Context.NOTIFICATION_SERVICE);
        MediaPlayer player = PodcastrApplication.newInstance().getMediaPlayer();
        if(player.isPlaying()){
            rm.setImageViewResource(R.id.pause, R.drawable.ic_action_play);
        }else{
            rm.setImageViewResource(R.id.pause, R.drawable.ic_action_pause);
        }

        Notification notif =  new NotificationCompat.Builder(getApplicationContext())
        .setOngoing(true)
        .setSmallIcon(R.drawable.ic_launcher)
        .setContent(rm)
        .build();

        mgr.notify(NOTIFICATION_ID, notif);
}  

Re-issuing the notification with the same ID updates the notification.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM