Я расскажу о том, чего я пытаюсь достичь. В своей деятельности я использую Alarm Manager для отправки ожидающего намерения получателю широковещательной рассылки ( 'NotificationBroadcastReceiver' ), задачей которого является показ уведомлений. Когда пользователь нажимает на кнопки действий (SNOOZE и POSTPONE), он отправляет широковещательную рассылку другому получателю ( 'NotificationActionReceiver' ), который затем выполняет соответствующее действие - если он откладывается, он отправляет сигнал тревоги несколько позже отправьте широковещательную рассылку на 'NotificationBroadcastReceiver' (чтобы можно было отобразить уведомление ЖЕ ).
Вот в чем проблема. Действия DONE и POSTPONE выполняются на 2 разных отложенных намерениях, и хотя я предоставляю им разные аргументы, срабатывает только один для Postpone. Где я допустил ошибку?
NotificationBroadcastReceiver:
package com.coffeetech.kittycatch;
import android.app.AlarmManager;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.os.Build;
import androidx.core.app.NotificationCompat;
import androidx.core.app.NotificationManagerCompat;
public class NotificationBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
int type; // 0 for Daily reminder, 1 for Shopping reminder
type = intent.getIntExtra("reminder", -1);
//below code for action
Intent postponeIntent, doneIntent;
PendingIntent postponePendingIntent, donePendingIntent;
postponeIntent = new Intent(context,NotificationActionReceiver.class);
postponeIntent.setAction("postpone");
postponeIntent.putExtra("type",type);
doneIntent = new Intent(context,NotificationActionReceiver.class);
postponeIntent.setAction("done");
doneIntent.putExtra("type",type);
//MAYBE THE PROBLEM IS IN THE BELOW 2 LINES
postponePendingIntent = PendingIntent.getBroadcast(context,3,postponeIntent,PendingIntent.FLAG_CANCEL_CURRENT);
donePendingIntent = PendingIntent.getBroadcast(context,4,doneIntent,PendingIntent.FLAG_CANCEL_CURRENT);
//below code for user tap on notification
Intent reminderIntent = new Intent(context, MainActivity.class);
reminderIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, reminderIntent, 0);
String title, text;
switch (type) {
case 0: //FOR EVERYDAY NOTIFICATIONS
title = "Daily Reminder";
text = "Time to update the quantities";
break;
case 1: //BELOW CODE TO MAKE AND SHOW SHOPPING NOTIFICATION
title = "Shopping Reminder";
text = "You need to buy certain things!";
break;
default:
title = "ERROR";
text = "in the Broadcast Receiver";
}
try {
NotificationCompat.Builder builder = new NotificationCompat.Builder(context, "kitty catch notification")
.setSmallIcon(R.drawable.ic_stat_name)
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setContentIntent(pendingIntent)
.setAutoCancel(false)
.setAllowSystemGeneratedContextualActions(false)
.setContentTitle(title)
.setContentText(text)
.setCategory(NotificationCompat.CATEGORY_REMINDER)
.setLargeIcon(BitmapFactory.decodeResource(context.getPackageManager().getResourcesForApplication("com.coffeetech.kittycatch"), R.drawable.ic_launcher_foreground))
.addAction(R.drawable.ic_snooze, "POSTPONE", postponePendingIntent)
.addAction(R.drawable.ic_done, "DONE", donePendingIntent);
// notificationId is a unique int for each notification that you must define
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(context);
notificationManager.notify(type, builder.build());
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
}
}
NotificationActionReceiver:
package com.coffeetech.kittycatch;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.widget.Toast;
import androidx.core.app.NotificationCompat;
import androidx.core.app.NotificationManagerCompat;
public class NotificationActionReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
int type = intent.getIntExtra("type", -1);
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(context);
//remove existing notification
notificationManager.cancel(type);
if(action == "done"){
if(type == 1) {
Intent doneIntent = new Intent("reset");
doneIntent.putExtra("reset", true);
context.sendBroadcast(doneIntent);
}
}else{
Intent snoozeIntent = new Intent(context, NotificationBroadcastReceiver.class);
snoozeIntent.putExtra("reminder", type);
snoozeIntent.setAction("another notification");
PendingIntent pendingIntent = null;
//try {
//pendingIntent = PendingIntent.getBroadcast(context.createPackageContext("com.coffeetech.kittycatch",0), 8, snoozeIntent, PendingIntent.FLAG_CANCEL_CURRENT);
pendingIntent = PendingIntent.getBroadcast(context, 8, snoozeIntent, PendingIntent.FLAG_CANCEL_CURRENT);
//} catch (PackageManager.NameNotFoundException e) {
// e.printStackTrace();
//}
int minutes = 1;
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
alarmManager.cancel(pendingIntent);
alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + minutes * 60000, pendingIntent);
}
}
}