Отклонить постоянное оповещение по Android через кнопку действия без открытия приложения
У меня есть приложение, в котором есть постоянное уведомление, чтобы помочь с запоминанием. Я хочу, чтобы увольнять это уведомление с помощью одной из кнопок действий, но я не хочу открывать приложение при нажатии кнопки. Я бы предпочел использовать встроенные кнопки действий уведомления и не создавать объект RemoteViews для заполнения уведомления. Я видел одно упоминание об использовании BroadcastReceiver на этой кнопке, которое было получено в моем приложении, и хотя его учебник был совершенно бесполезным, похоже, что это направлено в правильном направлении.
Intent resultIntent = new Intent(getBaseContext(), Dashboard.class);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(getBaseContext());
stackBuilder.addParentStack(Dashboard.class);
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent =
stackBuilder.getPendingIntent(
0,
PendingIntent.FLAG_UPDATE_CURRENT
);
Intent cancel = new Intent(getBaseContext(), CancelNotification.class);
stackBuilder.addParentStack(Dashboard.class);
stackBuilder.addNextIntent(cancel);
PendingIntent pendingCancel =
stackBuilder.getPendingIntent(
0,
PendingIntent.FLAG_UPDATE_CURRENT
);
NotificationCompat.Builder mb = new NotificationCompat.Builder(getBaseContext());
mb.setSmallIcon(R.drawable.cross_icon);
mb.setContentTitle(ref);
mb.setContentText(ver);
mb.setPriority(NotificationCompat.PRIORITY_LOW);
mb.setOngoing(true);
mb.setStyle(new NotificationCompat.BigTextStyle().bigText(ver));
mb.setContentIntent(resultPendingIntent);
mb.addAction(R.drawable.ic_cancel_dark, "Dismiss", pendingCancel);
manager.notify(1, mb.build());
Ответы
Ответ 1
Начните с этого:
int final NOTIFICATION_ID = 1;
//Create an Intent for the BroadcastReceiver
Intent buttonIntent = new Intent(context, ButtonReceiver.class);
buttonIntent.putExtra("notificationId",NOTIFICATION_ID);
//Create the PendingIntent
PendingIntent btPendingIntent = PendingIntent.getBroadcast(context, 0, buttonIntent,0);
//Pass this PendingIntent to addAction method of Intent Builder
NotificationCompat.Builder mb = new NotificationCompat.Builder(getBaseContext());
.....
.....
.....
mb.addAction(R.drawable.ic_Action, "My Action", btPendingIntent);
manager.notify(NOTIFICATION_ID, mb.build());
Создайте BroadcastReceiver:
public class ButtonReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
int notificationId = intent.getIntExtra("notificationId", 0);
// Do what you want were.
..............
..............
// if you want cancel notification
NotificationManager manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
manager.cancel(notificationId);
}
}
Если вы не хотите показывать какие-либо действия, когда пользователь нажимает на уведомление, определите намерение, переданное в setContentIntent
следующим образом:
PendingIntent resultPendingIntent = PendingIntent.getActivity(context, 0, new Intent(), 0);
......
......
mb.setContentIntent(resultPendingIntent);
Чтобы закрыть setAutoCancel()
уведомлений при нажатии, вызовите setAutoCancel()
со значением true при создании уведомления: mb.setAutoCancel(true);
Ответ 2
Принятое решение не работает в Android 8.1 и выше.
Выполните те же действия, что и в принятом ответе, но обновите эту строку:
//Create the PendingIntent
PendingIntent btPendingIntent = PendingIntent.getBroadcast(context, 0, buttonIntent, PendingIntent.FLAG_UPDATE_CURRENT);
Смотрите также PendingIntent.FLAG_UPDATE_CURRENT