Last active
January 28, 2016 17:18
-
-
Save gturedi/e89bc49560ec047780ad to your computer and use it in GitHub Desktop.
simple util class to run periodic tasks on android
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package gturedi.sample; | |
import android.content.Context; | |
import android.content.SharedPreferences; | |
public class PeriodicTask { | |
private static final int ONE_DAY_IN_MILLIS = 1000 * 60 * 60 * 24; | |
public static void run(final Context context, Runnable runnable) { | |
run(context, "task", 2, runnable); | |
} | |
public static void run(final Context context, String taskName, int periodInDays, Runnable runnable) { | |
SharedPreferences preferences = context.getSharedPreferences(taskName, Context.MODE_PRIVATE); | |
long lastTime = preferences.getLong(taskName, 0); | |
long now = System.currentTimeMillis(); | |
int diff = (int) ((now - lastTime) / ONE_DAY_IN_MILLIS); | |
if (diff >= periodInDays) { | |
preferences.edit().putLong(taskName, now).commit(); | |
new Thread(runnable).start(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment