Android set repeating alarm for certain time of day

我怕爱的太早我们不能终老 提交于 2020-01-11 11:16:48

问题


I am trying to set a repeating alarm that will will download a file every minute but only between 8:00 and 22:00. I feel like I'm really close but I can't see the error I'm making. Currently the broadcast receiver is not activating. If set the repeating alarm manually to alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis()+10000, 60000,pendingIntent); it works fine. Any guidance would be much appreciated.

protected void scheduleNextUpdate()
      {
        Intent intent = new Intent("TEST");
        PendingIntent pendingIntent =
            PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
        int updateInterval =  1;
        long nextUpdate =(60000 * updateInterval);

        long currentTimeMillis = System.currentTimeMillis();


        long nextUpdateTimeMillis = currentTimeMillis + nextUpdate;
        Time nextUpdateTime = new Time();
        nextUpdateTime.set(nextUpdateTimeMillis);

        if (nextUpdateTime.hour < 8 || nextUpdateTime.hour > 22)
        {
          nextUpdateTime.hour = 8;
          nextUpdateTime.minute = 0;
          nextUpdateTime.second = 0;
          nextUpdateTimeMillis = nextUpdateTime.toMillis(false) + DateUtils.DAY_IN_MILLIS;
        }

        AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
        alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis()+10000, nextUpdateTimeMillis,pendingIntent);

        boolean alarmUp = (PendingIntent.getBroadcast(this, 0, 
                new Intent("TEST"), 
                PendingIntent.FLAG_NO_CREATE) != null);

        if (alarmUp)
        {
            Log.d("myTag", "Alarm is already active");
        }
  }

回答1:


You should set your alarm reapeating when it is between 8:00 and 22:00 like you mentioned:

alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis()+10000, 60000,pendingIntent); 

This will repeat every minute. But you must explicitly cancel the alarm. You can cancel it after download is completed, by checking if its already 22:00. Or by another alarm that will be triggered when it is 22:00. Otherwise it will not stop.

use alarmManager.cancel (pendingIntent)

described here: http://developer.android.com/reference/android/app/AlarmManager.html#cancel(android.app.PendingIntent

Hope this helps.



来源:https://stackoverflow.com/questions/13605840/android-set-repeating-alarm-for-certain-time-of-day

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!