Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Schedule a pending intent in android.
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.os.SystemClock;
import android.util.Log;
public class Backoff
{
private static String TAG = "Backoff";
private static long INITIAL_RETRY_TIME = 400;
private static int MAX_RETRIES = 20;
/*
0: 400 ms (0.0 hr)
1: 800 ms (0.0 hr)
2: 1600 ms (0.0 hr)
3: 3200 ms (0.0 hr)
4: 6400 ms (0.0 hr)
5: 12800 ms (0.0 hr)
6: 25600 ms (0.01 hr)
7: 51200 ms (0.01 hr)
8: 102400 ms (0.03 hr)
9: 204800 ms (0.06 hr)
10: 409600 ms (0.11 hr)
11: 819200 ms (0.23 hr)
12: 1638400 ms (0.46 hr)
13: 3276800 ms (0.91 hr)
14: 6553600 ms (1.82 hr)
15: 13107200 ms (3.64 hr)
16: 26214400 ms (7.28 hr)
17: 52428800 ms (14.56 hr)
18: 104857600 ms (29.13 hr)
19: 209715200 ms (58.25 hr)
20: 419430400 ms (116.51 hr)
*/
public static void schedule(Context context, PendingIntent intent, int count)
{
if (count <= MAX_RETRIES)
{
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
long multiplier = 1L << count;
long timeFromNow = multiplier * INITIAL_RETRY_TIME;
long retryAt = SystemClock.elapsedRealtime() + timeFromNow;
Log.d(TAG, "Scheduling a retry in " + timeFromNow + " ms from now");
alarmManager.set(AlarmManager.RTC, retryAt, intent);
} else
{
Log.d(TAG, "Too many retries, no more.");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.