每天每小时触发警报

时间:2018-11-10 07:38:29

标签: java android android-studio alarmmanager alarm

我想按小时触发警报,例如从早上6点至下午6点,并且每天从早上6点至下午6点触发警报。 我需要多重警报吗? 需要帮助

Intent intent1 = new Intent(context, cls);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(context, DAILY_REMINDER_REQUEST_CODE, intent1, PendingIntent.FLAG_UPDATE_CURRENT);
    AlarmManager am = (AlarmManager) context.getSystemService(ALARM_SERVICE);
    am.setInexactRepeating(AlarmManager.RTC_WAKEUP,setcalendar.getTimeInMillis(), AlarmManager.INTERVAL_HOUR, pendingIntent);
  //  
    Toast.makeText(context, "Notification Alarm set", Toast.LENGTH_SHORT).show();

上述警报仅每天一次触发一次,但我希望每天每天触发一次

1 个答案:

答案 0 :(得分:0)

如果每天早上6点至下午6点之间会一直重复 ,则您不需要数据库。另外,请确保您将警报安排到IntentService中的BroadcastReceiverPendingIntent。在onReceive中获取当前时间,检查是否在上午6点至下午6点之间,如果有,则发出火警。如果不是,请取消当前警报(节省电池),将下一个警报安排为上午6点。同时编写一种检查当天的算法。我在示例代码中留在TODO中的详细信息。

    Calendar calendar = Calendar.getInstance();
    int hour = calendar.get(Calendar.HOUR_OF_DAY);
    if (hour >= 6 && hour <= 18){
        //fire alarm
    } else if (hour > 19 || hour < 6) {
        Intent intent1 = new Intent(context, cls);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(context, DAILY_REMINDER_REQUEST_CODE, intent1, PendingIntent.FLAG_CANCEL_CURRENT);
        pendingIntent.cancel();
        calendar.set(Calendar.HOUR_OF_DAY, 6);
        //TODO: Write an algorithm that checks if current day + 1 will be still in the same month,
        //TODO: what I mean if it is out of range of month, e.g 30th of Febraury, then get current month and add 1
        //TODO: If there is currently 31st December, change day to be equal of 1, get current year, add 1 etc.
        int currentday = calendar.get(Calendar.DAY_OF_MONTH);
        calendar.set(Calendar.DAY_OF_MONTH, currentday + 1);
        Intent intent1 = new Intent(context, cls);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(context, DAILY_REMINDER_REQUEST_CODE, intent1, PendingIntent.FLAG_UPDATE_CURRENT);
        AlarmManager am = (AlarmManager) context.getSystemService(ALARM_SERVICE);
        am.setInexactRepeating(AlarmManager.RTC_WAKEUP,setcalendar.getTimeInMillis(), AlarmManager.INTERVAL_HOUR, pendingIntent);
    }