每次启动应用程序时都可以创建警报吗?

时间:2015-01-23 16:37:08

标签: android android-intent alarmmanager

我的应用程序会创建一个每天重复的警报。由于无法知道警报是否已经注册,因此每次启动应用程序时都会创建警报。

这是在主要活动开始时调用的函数(在onCreate()内部):

public static void setAlarm(Context context) {
    Intent intent = new Intent(context, AlarmReceiver.class);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent, 0);

    AlarmManager alarmManager = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);

    Calendar firingCal = Calendar.getInstance(TimeZone.getTimeZone("Europe/Paris"));
    Calendar currentCal = (Calendar)firingCal.clone();

    Random rnd = new Random();

    // Each day between 1:00 AM and 1:30 AM (some jitter added)
    firingCal.set(Calendar.HOUR_OF_DAY, 1);
    firingCal.set(Calendar.MINUTE, rnd.nextInt(30));
    firingCal.set(Calendar.SECOND, 0);

    long intendedTime = firingCal.getTimeInMillis();
    long currentTime = currentCal.getTimeInMillis();

    if (intendedTime >= currentTime) {
        //set from today
        alarmManager.setInexactRepeating(AlarmManager.RTC, intendedTime, AlarmManager.INTERVAL_DAY, pendingIntent);
    } else {
        //set from next day
        firingCal.add(Calendar.DAY_OF_MONTH, 1);
        intendedTime = firingCal.getTimeInMillis();

        alarmManager.setInexactRepeating(AlarmManager.RTC, intendedTime, AlarmManager.INTERVAL_DAY, pendingIntent);
    }
}

每次启动应用程序时都可以重新创建警报吗?我应该在PendingIntent上使用一些标志(比如更新或取消现有的PendingIntent)吗?

谢谢!

更新:如果从性能角度使用标志0而不是PendingIntent.FLAG_UPDATE_CURRENT,这是一个问题吗?

0 个答案:

没有答案