В моем приложении для Android есть опция, позволяющая пользователю устанавливать уведомления столько, сколько он хочет.Я использовал BroadcastReceiver
, и он работает для последнего уведомления, но только для одного.
NotifLabel - это POJO с атрибутом, который я использую в уведомлении.Я попытался упростить код и сделать его более общим для всех.
Вот моя реализация этой функции:
AlarmReceiver.java
public class AlarmReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Formula formula = DatabaseManager.getInstance().getRandomFormula(context);
final int not_nu=generateRandom();
SecurePreferences preferences = new SecurePreferences(context, "PREFERENCE", secretKey, true);
NotificationManager nm = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
Intent notificationIntent = new Intent(context, MainActivity.class);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
| Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent pendingI = PendingIntent.getActivity(context, not_nu,
notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel("default",
"Daily Notification",
NotificationManager.IMPORTANCE_DEFAULT);
channel.setDescription("Daily Notification");
if (nm != null) {
nm.createNotificationChannel(channel);
}
}
NotificationCompat.Builder b = new NotificationCompat.Builder(context, "default");
b.setAutoCancel(true)
.setDefaults(NotificationCompat.DEFAULT_ALL)
.setWhen(System.currentTimeMillis())
.setTicker("{Time to watch some cool stuff!}")
.setContentTitle("My notification :")
.setContentText("blabla")
.setContentInfo("INFO")
.addAction(0, "Open", pendingI)
.setContentIntent(pendingI);
if (nm != null) {
nm.notify(not_nu, b.build());
Calendar nextNotifyTime = Calendar.getInstance();
nextNotifyTime.add(Calendar.DATE, 1);
preferences.putLong("nextNotifyTime", nextNotifyTime.getTimeInMillis());
}
}
public int generateRandom(){
Random random = new Random();
return random.nextInt(9999 - 1000) + 1000;
}
}
DeviceBootReceiver.java
public class DeviceBootReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if (Objects.equals(intent.getAction(), "android.intent.action.BOOT_COMPLETED")) {
int index = 0;
ArrayList<NotifLabel> listNotifs = new ArrayList<>();
listNotifs.add(new NotifLabel(0, true, 15, 27));
listNotifs.add(new NotifLabel(0, true, 15, 28));
for(NotifLabel notif : listNotifs) {
// on device boot complete, reset the alarm
Intent alarmIntent = new Intent(context, AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context,
new Random().nextInt(9999 - 1000) + 1000,
alarmIntent, PendingIntent.FLAG_CANCEL_CURRENT);
AlarmManager manager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
SecurePreferences preferences = new SecurePreferences(context, "PREFERENCE", secretKey, true);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.HOUR_OF_DAY, notif.getHour());
calendar.set(Calendar.MINUTE, notif.getMinute());
calendar.set(Calendar.SECOND, 1);
Calendar newC = new GregorianCalendar();
newC.setTimeInMillis(preferences.getLong("nextNotifyTime", Calendar.getInstance().getTimeInMillis()));
if (calendar.after(newC)) {
calendar.add(Calendar.HOUR, 1);
}
if (manager != null) {
manager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
AlarmManager.INTERVAL_DAY, pendingIntent);
}
index = index + 1;
}
}
}
}
NotifLabel.java
public class NotifLabel {
private int typeOfNotification;
private boolean state;
private int hour;
private int minute;
public NotifLabel(int typeOfNotification, boolean state, int hour, int minute) {
this.typeOfNotification = typeOfNotification;
this.state = state;
this.hour = hour;
this.minute = minute;
}
public int getTypeOfNotification() {
return typeOfNotification;
}
public boolean isState() {
return state;
}
public int getHour() {
return hour;
}
public int getMinute() {
return minute;
}
}