Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have been developing an Android application and I need to execute 1 task every hour. I uses the following code for it:

private static final long ALARM_PERIOD = 1000L;

public static void initAlarmManager(Context context) {

    Editor editor=PreferenceManager.getDefaultSharedPreferences(context).edit();
    editor.putBoolean(context.getString(R.string.terminate_key), true).commit();

    AlarmManager manager = (AlarmManager) context.getSystemService(context.ALARM_SERVICE);
    Intent i = new Intent(context, AlarmEventReceiver.class);
    PendingIntent receiver = PendingIntent.getBroadcast(context, 0, i, 0);
    manager.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
            SystemClock.elapsedRealtime(), ALARM_PERIOD, receiver);
}

It works for me, but my client tells me that the task works only 1 time and won't work 1 hour. Where have I made a mistake? Please, tell me. Thank you.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
185 views
Welcome To Ask or Share your Answers For Others

1 Answer

According to your code, ALARM_PERIOD is 1000L, as repeating interval. So I doubt the alarm will set of in every 1000 milliseconds.

if you are setting repeating interval for every hour, it should be 3600000L. And take note that if the phone is restarted, your alarm manager will no longer work unless you start again.

Here is the my Code:

private void setAlarmManager() {
    Intent intent = new Intent(this, AlarmReceiver.class);
    PendingIntent sender = PendingIntent.getBroadcast(this, 2, intent, 0);
    AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
    long l = new Date().getTime();
    if (l < new Date().getTime()) {
        l += 86400000; // start at next 24 hour
    }
    am.setRepeating(AlarmManager.RTC_WAKEUP, l, 86400000, sender); // 86400000
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...