使用BroadcastReceiver的多个每日通知

时间:2018-10-01 13:40:06

标签: java android broadcastreceiver

我在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;
    }
}

0 个答案:

没有答案