首页 > 解决方案 > Android 警报管理器不适用于特定日期和时间

问题描述

所以我一直在开发药物摄入应用程序,我需要在本地提醒用户(不需要互联网/推送通知)服用他们的药物。我正在为此使用 Android 警报管理器。以下是代码注意我正在尝试将警报安排在特定日期:“2018 年 7 月 13 日下午 3 点 30 分”。我安排并等待,但提醒没有触发(所以没有广播)但是如果我使用具有定义的毫秒量的AlarmManager.ELAPSED_REALTIME_WAKEUP它会触发(但 AlarmManager.RTC_WAKEUP只是不起作用)`

    AlarmManager manager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
    Intent myIntent;
    PendingIntent pendingIntent;
    long reminderDateTimeInMilliseconds = 000;

    myIntent = new Intent(this,MedicationScheduleBroadCastReceiver.class);

    pendingIntent = PendingIntent.getBroadcast(this,0,myIntent,PendingIntent.FLAG_UPDATE_CURRENT);

    //TODO : Reminder the user to take medication on the 13th July 2018 at 15:30
    Calendar calendarToSchedule = Calendar.getInstance();

    calendarToSchedule.set(Calendar.YEAR, 2018);
    calendarToSchedule.set(Calendar.MONTH, 07);
    calendarToSchedule.set(Calendar.DAY_OF_MONTH, 13);
    calendarToSchedule.set(Calendar.HOUR_OF_DAY, 15);
    calendarToSchedule.set(Calendar.MINUTE, 30);

    reminderDateTimeInMilliseconds = calendarToSchedule.getTimeInMillis();

    if(android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O){

        manager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, reminderDateTimeInMilliseconds, pendingIntent);
    }
    else{

        manager.set(AlarmManager.RTC_WAKEUP, reminderDateTimeInMilliseconds, pendingIntent);
    }

`

标签: javaandroidalarmmanagerandroid-alarms

解决方案


所以我发现了这个问题,主要问题是 Java 中的日历月实际上是基于 0 索引的所以(Jan:0 - Dec:11)所以下面是更新的代码。

AlarmManager manager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
Intent myIntent;
PendingIntent pendingIntent;
long reminderDateTimeInMilliseconds = 000;

myIntent = new Intent(this,MedicationScheduleBroadCastReceiver.class);

pendingIntent = PendingIntent.getBroadcast(this,0,myIntent,PendingIntent.FLAG_UPDATE_CURRENT);

//TODO : Reminder the user to take medication on the 13th July 2018 at 15:30
// Note: For the month of July the int value will actuall be 6 instead of 7
Calendar calendarToSchedule = Calendar.getInstance();
calendarToSchedule.setTimeInMillis(System.currentTimeMillis());
calendarToSchedule.clear();

//.Set(Year, Month, Day, Hour, Minutes, Seconds);
calendarToSchedule.set(2018, 06, 13, 15, 30, 0);


reminderDateTimeInMilliseconds = calendarToSchedule.getTimeInMillis();

if(android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O){

    manager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, reminderDateTimeInMilliseconds, pendingIntent);
}
else{

    manager.set(AlarmManager.RTC_WAKEUP, reminderDateTimeInMilliseconds, pendingIntent);
}

推荐阅读