Alarm Notification fires instantly. Android

后端 未结 5 2016
忘掉有多难
忘掉有多难 2021-02-15 18:15

I am working on a Reminder that sends notification on fixed time to the user.

The alarm is getting off instantly ...

I tried most of the suggestions over s

5条回答
  •  感动是毒
    2021-02-15 19:08

    I have the same issue before, please check the following details:

    Not working code sample:

    Intent notificationIntent = new Intent("~~~.BaseActivity");
            notificationIntent.putExtra("type", 2);
            notificationIntent.putExtra("appName", "testApp");
            notificationIntent.putExtra("messageEN", "Good evening");
            notificationIntent.putExtra("notificaitonID", 4);
    
    
            PendingIntent broadcast = PendingIntent.getBroadcast(context, 4,
                    notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
            Calendar calendar = Calendar.getInstance();
            calendar.set(Calendar.HOUR_OF_DAY, 18);
            calendar.set(Calendar.MINUTE, 10);
            calendar.set(Calendar.SECOND, 0);
            // this is to show it at the 6:10 
    
            AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    
    
    
            alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,
                        calendar.getTimeInMillis(),
                        AlarmManager.INTERVAL_DAY,
                        broadcast);
    

    Working Code:

        Intent notificationIntent = new Intent("~~~.BaseActivity");
        notificationIntent.putExtra("type", 2);
        notificationIntent.putExtra("appName", "testApp");
        notificationIntent.putExtra("messageEN", "Good evening");
        notificationIntent.putExtra("notificaitonID", 4);
    
    
        PendingIntent broadcast = PendingIntent.getBroadcast(context, 4,
                notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.HOUR_OF_DAY, 18);
        calendar.set(Calendar.MINUTE, 10);
        calendar.set(Calendar.SECOND, 0);
        // this is to show it at the 6:10 
    
        AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    
    
        Calendar nowCalendar = Calendar.getInstance();
    
        if (calendar.after(nowCalendar)) {
            alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,
                    calendar.getTimeInMillis(),
                    AlarmManager.INTERVAL_DAY,
                    broadcast);
    
        } else {
            calendar.add(Calendar.DAY_OF_MONTH, 1);
            alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,
                    calendar.getTimeInMillis(),
                    AlarmManager.INTERVAL_DAY,
                    broadcast);
        }
    

    it's done only when you about to set the repeating, you need to check if it's passed or not, and if it's passed just add the wanted time for repeating

提交回复
热议问题