Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
368 views
in Technique[技术] by (71.8m points)

alarmmanager - How to show multiple alarm notifications in android

I am trying to generate multiple notifications as per user set alarm. It was not working when i add multiple alarms. I'm generating random number for each creations of alarm. This is My Alarm Receiver class.

public class AlarmReceiver extends BroadcastReceiver {

    private static final String BUNDLE_EXTRA = "bundle_extra";
    private static final String ALARM_KEY = "alarm_key";
    public static String TAG = AlarmReceiver.class.getName();

    @Override
    public void onReceive(Context context, Intent intent) {

        final AlarmMedicineModel alarm = intent.getBundleExtra(BUNDLE_EXTRA).getParcelable(ALARM_KEY);

        Log.d(TAG,"System time>>>>>>>>>>>>>");

        String CHANNEL_ID = "my_channel_01"; // The id of the channel.

        int id = alarm.getId();
        Log.d(TAG,"Notification id >>>>>>>>>>>>>>>>>>>"+id);
        CharSequence name = "test";// The user-visible name of the channel.
        int importance = NotificationManager.IMPORTANCE_HIGH;
        NotificationChannel mChannel = null;
        if (SDK_INT >= Build.VERSION_CODES.O) {
            mChannel = new NotificationChannel(CHANNEL_ID, name, importance);
        }
        Uri defaultSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context);
        mBuilder.setSmallIcon(R.drawable.logs);
        mBuilder.setSound(defaultSound);
        mBuilder.setContentTitle("Dr.Trust");
        mBuilder.setAutoCancel(true);
        mBuilder.setContentText(alarm.getLabelName());
        mBuilder.setChannelId(CHANNEL_ID);

        NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        if (SDK_INT >= Build.VERSION_CODES.O) {
            mNotificationManager.createNotificationChannel(mChannel);
        }

        mNotificationManager.notify(id, mBuilder.build());

        setAlarmReminder(context,alarm);

    }

    public static void setAlarmReminder(Context context, AlarmMedicineModel alarmMedicineModel){

        boolean  active = isAlarmActive(alarmMedicineModel);
        if(!active){
            cancelReminderAlarm(context,alarmMedicineModel);
            return;
        }

        final Calendar nextAlarmTime = getTimeForNextAlarm(alarmMedicineModel);
        alarmMedicineModel.setTime(nextAlarmTime.getTimeInMillis());

        final Intent intent = new Intent(context, AlarmReceiver.class);
        final Bundle bundle = new Bundle();
        bundle.putParcelable(ALARM_KEY, alarmMedicineModel);
        intent.putExtra(BUNDLE_EXTRA, bundle);

        final int id = alarmMedicineModel.getId();
        Log.d(TAG,"Notification ID >>>>>>>>>>>>>>>: "+id);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(context, id,
                intent, FLAG_UPDATE_CURRENT);

        ScheduleAlarm.with(context).schedule(alarmMedicineModel, pendingIntent);

    }

    public static void setReminderAlarm(Context context, List<AlarmMedicineModel> alarms) {
        for(AlarmMedicineModel alarm : alarms) {
            setAlarmReminder(context,alarm);
        }
    }

    private static boolean isAlarmActive(AlarmMedicineModel alarmMedicineModel) {
        boolean isActive = false;
        List<Integer> daysList = new ArrayList<>();
        daysList.add(alarmMedicineModel.getMon());
        daysList.add(alarmMedicineModel.getTue());
        daysList.add(alarmMedicineModel.getWed());
        daysList.add(alarmMedicineModel.getThu());
        daysList.add(alarmMedicineModel.getFri());
        daysList.add(alarmMedicineModel.getSat());
        daysList.add(alarmMedicineModel.getSun());
        Log.d(TAG,"days List are :::"+daysList.toString());
        for(int i=0;i<daysList.size();i++){
            if(daysList.get(i) == 1){
                isActive = true;
            }
        }
        return isActive;
    }

    private static Calendar getTimeForNextAlarm(AlarmMedicineModel alarm) {

        final Calendar calendar = Calendar.getInstance();

        calendar.setTimeInMillis(alarm.getTime());

        final long currentTime = System.currentTimeMillis();

        final int startIndex = getStartIndexFromTime(calendar);

        Log.d(TAG,"Start Index >>>>>>>"+startIndex);

        int count = 0;

        boolean isAlarmSetForDay = false;

        int mon = alarm.getMon();
        int tue = alarm.getTue();
        int wed = alarm.getWed();
        int thu = alarm.getThu();
        int fri = alarm.getFri();
        int sat = alarm.getSat();
        int sun = alarm.getSun();
        List<Integer> days = new ArrayList<>();
        days.add(mon);
        days.add(tue);
        days.add(wed);
        days.add(thu);
        days.add(fri);
        days.add(sat);
        days.add(sun);

        do {
            final int index = (startIndex + count) % 7;

            int daysExits = days.get(index);
            if(daysExits == 1 && calendar.getTimeInMillis() > currentTime){
                isAlarmSetForDay = true;
                if(!isAlarmSetForDay) {
                    calendar.add(Calendar.DAY_OF_MONTH, 1);
                    count++;
                }
            }
        } while(!isAlarmSetForDay && count < 7);

        return calendar;

    }

    private static int getStartIndexFromTime(Calendar c) {

        final int dayOfWeek = c.get(Calendar.DAY_OF_WEEK);

        int startIndex = 0;

        switch (dayOfWeek) {
            case Calendar.MONDAY:
                startIndex = 0;
                break;
            case Calendar.TUESDAY:
                startIndex = 1;
                break;
            case Calendar.WEDNESDAY:
                startIndex = 2;
                break;
            case Calendar.THURSDAY:
                startIndex = 3;
                break;
            case Calendar.FRIDAY:
                startIndex = 4;
                break;
            case Calendar.SATURDAY:
                startIndex = 5;
                break;
            case Calendar.SUNDAY:
                startIndex = 6;
                break;
        }

        return startIndex;

    }

    private static class ScheduleAlarm {

        @NonNull
        private final Context ctx;
        @NonNull private final AlarmManager am;

        private ScheduleAlarm(@NonNull AlarmManager am, @NonNull Context ctx) {
            this.am = am;
            this.ctx = ctx;
        }

        static ScheduleAlarm with(Context context) {
            final AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
            if(am == null) {
                throw new IllegalStateException("AlarmManager is null");
            }
            return new ScheduleAlarm(am, context);
        }

        void schedule(AlarmMedicineModel alarm, PendingIntent pi) {
            am.set(AlarmManager.RTC_WAKEUP,alarm.getTime(),pi);
            Log.d(TAG,"Alarm Scheduled>>>>>>>>>>>>");
        }
    }

    public static void cancelReminderAlarm(Context context, AlarmMedicineModel alarm) {

        final Intent intent = new Intent(context, AlarmReceiver.class);
        final PendingIntent pIntent = PendingIntent.getBroadcast(
                context,
                alarm.getId(),
                intent,
                FLAG_UPDATE_CURRENT
        );

        final AlarmManager manager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        manager.cancel(pIntent);
    }
}

Here is the setting alarm

 Random random = new Random();
               int id = random.nextInt(1000);
               Calendar calendar = Calendar.getInstance();
               calendar.set(Calendar.MINUTE,mdTimePicker.getCurrentMinute());
               calendar.set(Calendar.HOUR_OF_DAY,mdTimePicker.getCurrentHour());

               AlarmMedicineModel alarm = new AlarmMedicineModel();
               alarm.setTime(calendar.getTimeInMillis());
               alarm.setId(id);
               alarm.setLabelName(etMdLabel.getText().toString());
               alarm.setMon(monClick);
               alarm.setTue(tueClick);
               alarm.setWed(wedClick);
               alarm.setThu(thuClick);
               alarm.setFri(friClick);
               alarm.setSat(satClick);
               alarm.setSun(sunClick);

               AlarmReceiver.setAlarmReminder(getApplicationContext(),alarm)

;

Example If I set the two alarm. The first alarm notification will show. The second alarm notification not showing. What was the mistake in my code. Can anyone please guide me..how to resolve this issue.

Thanks in Advance. Amar.

question from:https://stackoverflow.com/questions/66045358/how-to-show-multiple-alarm-notifications-in-android

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...