Android | setAlartm每天都在同一时间|不工作

时间:2016-06-15 20:05:22

标签: android alarmmanager

在我的Android应用中,我会每天凌晨3点发出命令,并使用AlarmManagersetRepeating。当应用程序启动时,我这样做:

Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY, 3);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
Intent intent = new Intent(context, MyBroadcast.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context.getApplicationContext(), 1253, intent, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pendingIntent);

这是 MyBroadcast

public class MyBroadcast extends BroadcastReceiver{
    public void onReceive(Context context, Intent intent) {
        // TODO Auto-generated method stub
        Log.d("ALARM","Alarm worked.");
    }
}

购买,而不是在3运行命令,应用程序立即运行命令。为什么呢?

1 个答案:

答案 0 :(得分:2)

当警报设置为通过日期时,它会立即触发,如果你不想要你可以创建一些逻辑只能在今天启动它,如果当前时间早于凌晨3点,这样的事情会起作用:

    Calendar now = Calendar.getInstance();
    Calendar cal = Calendar.getInstance();
    cal.set(Calendar.HOUR_OF_DAY, 3);
    cal.set(Calendar.MINUTE, 0);
    cal.set(Calendar.SECOND, 0);
    Intent intent = new Intent(context, MyBroadcast.class);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(context.getApplicationContext(), 1253, intent, PendingIntent.FLAG_UPDATE_CURRENT);
    AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    if (now.before(cal)) {
        alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pendingIntent);
    } 
    else {
        cal.set(Calendar.DAY_OF_YEAR, now.get(Calendar.DAY_OF_YEAR) +1);
        alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pendingIntent);   
    }

我们创建了另一个日历作为当前时间的参考,并检查我们是否在凌晨3点之前,如果没有,则仅在第二天之后调用警报。