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

Categories

0 votes
186 views
in Technique[技术] by (71.8m points)

java - How to execute one task every hour?

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

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

1 Answer

0 votes
by (71.8m points)

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
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...