как изменить флажок очистки уведомления при нажатии кнопки уведомления - PullRequest
0 голосов
/ 29 августа 2018

Я разрабатываю потоковое приложение. Для этого я использую Exoplayer, поэтому во время воспроизведения показываю уведомление. В этом уведомлении у нас есть кнопка воспроизведения / паузы. когда мы приостанавливаем музыкальное уведомление, необходимо включить режим очистки, а когда мы играем, музыкальное уведомление не должно очищаться.

Это код уведомления

static RemoteViews notificationView;
static Notification notification;
static NotificationManager notificationManager;

private void startNotification() {
        String ns = Context.NOTIFICATION_SERVICE;
        notificationManager =
                (NotificationManager) getSystemService(ns);

        notification = new Notification(R.mipmap.ic_launcher, null,
                System.currentTimeMillis());

        notificationView = new RemoteViews(getPackageName(),
                R.layout.mynotification);

        if (isPlaying)
            notificationView.setInt(R.id.closeOnFlash, "setBackgroundResource", R.drawable.pausecontrol);
        else
            notificationView.setInt(R.id.closeOnFlash, "setBackgroundResource", R.drawable.playcontrol);

        notificationView.setTextViewText(R.id.appName, "Testing......");

        //the intent that is started when the notification is clicked (works)
        Intent notificationIntent = new Intent(this, MainActivity.class);
        notificationIntent.putExtra("play", "notify");

        editor = preferences.edit();
        editor.putString("play", "notify");
        editor.apply();

        PendingIntent pendingNotificationIntent = PendingIntent.getActivity(this, 11,
                notificationIntent, 0);

        notification.contentView = notificationView;
        notification.contentIntent = pendingNotificationIntent;

        if (isPlaying)
            notification.flags |= Notification.FLAG_NO_CLEAR;
        else
            notification.flags |= Notification.FLAG_AUTO_CANCEL;

        //this is the intent that is supposed to be called when the
        //button is clicked
        Intent intentPlay = new Intent(this, switchButtonListener.class);
        PendingIntent pendingSwitchIntent = PendingIntent.getBroadcast(this, 0
                intentPlay, PendingIntent.FLAG_NO_CREATE);
        notificationView.setOnClickPendingIntent(R.id.closeOnFlash, pendingSwitchIntent);


        notificationManager.notify(1, notification);
    }

А это код получателя

public static class switchButtonListener extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
                Log.d("Here", "I am play");
                if (exoPlayer.getPlayWhenReady()) {
                 exoPlayer.setPlayWhenReady(false);
                 btnPlay.setImageResource(android.R.drawable.ic_media_play);
                 notificationView.setInt(R.id.closeOnFlash, "setBackgroundResource", R.drawable.playcontrol);
                 notification.flags |= Notification.FLAG_AUTO_CANCEL;                    
                 notificationManager.notify(1, notification);
                 }else 
                 {
                exoPlayer.setPlayWhenReady(true);
                btnPlay.setImageResource(android.R.drawable.ic_media_pause);
                notificationView.setInt(R.id.closeOnFlash, "setBackgroundResource", R.drawable.pausecontrol);
               notification.flags |= Notification.FLAG_NO_CLEAR;
               notificationManager.notify(1, notification);
                }

        }
    }

Здесь проблема заключается в том, что когда вы нажимаете кнопку воспроизведения / паузы в уведомлении, тогда режим очистки уведомлений необходимо включать / отключать. Но это не работает, но когда мы нажимаем кнопку воспроизведения / паузы в действии, все работает нормально, потому что, когда я нажимаю кнопку с уведомлением, в этом методе уведомления я проверяю вот так

   if (isPlaying)
        notification.flags |= Notification.FLAG_NO_CLEAR;
    else
        notification.flags |= Notification.FLAG_AUTO_CANCEL;

Таким образом, при нажатии кнопки активности уведомление о включении / отключении работает нормально, но при нажатии кнопки уведомления не работает. но изображение кнопки воспроизведения / паузы также изменилось успешно, проблема заключается только в том, что включение / отключение уведомлений не работает. Но здесь есть еще одна проблема: когда мы приостанавливаем воспроизведение музыки с помощью кнопки уведомлений, затем нажимаем на открытое приложение уведомлений и закрытие уведомлений. Поэтому здесь проблема не может обновить флаг очистки в приемнике.

Так что, пожалуйста, объясните мне, как этого достичь, спасибо заранее .......

...