Android - 播放/暂停更新通知中的RemoteView

时间:2016-04-13 05:36:03

标签: android android-notifications remoteview

我试图通过框架布局在通知中实现播放/暂停按钮但是当我点击暂停mediaPlayer时它没有更新以显示通知中的播放按钮。如何更新视图?

RemoteViews nv = new RemoteViews(getPackageName(), R.layout.notificationLayout);
 Intent switchIntent = new Intent("com.example.android.ACTION_PLAY");
 PendingIntent pendingSwitchIntent = PendingIntent.getBroadcast(this, 100, switchIntent, 0);
 nv.setOnClickPendingIntent(R.id.pause, pendingSwitchIntent);

在广播接收器类

@Override

public void onReceive(Context context, Intent intent) {

            String action = intent.getAction();

            if(action.equalsIgnoreCase("com.example.app.ACTION_PLAY")){
                if(mp.isPlaying())
                {
                    nv.setViewVisibility(R.id.pause, View.INVISIBLE);
                    nv.setViewVisibility(R.id.play, View.VISIBLE);
                    mp.pause();
                }
                else
                {
                    nv.setViewVisibility(R.id.play, View.INVISIBLE);
                    nv.setViewVisibility(R.id.pause, View.VISIBLE);
                    mp.start();
                }

            }
        }  

2 个答案:

答案 0 :(得分:0)

试试!!!!

@Override

public void onReceive(Context context, Intent intent) {
Notification notification = null;
        String action = intent.getAction();

        if(action.equalsIgnoreCase("com.example.app.ACTION_PLAY")){
            if(mp.isPlaying())
            {
                notification.contentView.setViewVisibility(R.id.pause, View.INVISIBLE);
                notification.contentView.setViewVisibility(R.id.play, View.VISIBLE);
                mp.pause();
            }
            else
            {
                notification.contentView.setViewVisibility(R.id.play, View.INVISIBLE);
                notification.contentView.setViewVisibility(R.id.pause, View.VISIBLE);
                mp.start();
            }

        }
    }  

答案 1 :(得分:0)

您可以将另一个图标的新notification再次发布到前台以刷新远程视图。

RemoteViews可以重复使用,但在更改RemoteView的内容后应调用startForeground(NOTIFICATION_ID, mNotification);

我认为这是因为notification通过Parcel与系统通知进行通信,内容已经克隆到新实例。