Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@israteneda
Created December 26, 2019 14:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save israteneda/0ba1b449b2f901fef0fd78fefa5e27d6 to your computer and use it in GitHub Desktop.
Save israteneda/0ba1b449b2f901fef0fd78fefa5e27d6 to your computer and use it in GitHub Desktop.
Repeating task with handler
private int mInterval = 5000; // 5 seconds by default, can be changed later
private Handler mHandler;
@Override
protected void onCreate(Bundle bundle) {
// your code here
mHandler = new Handler();
startRepeatingTask();
}
@Override
public void onDestroy() {
super.onDestroy();
stopRepeatingTask();
}
Runnable mStatusChecker = new Runnable() {
@Override
public void run() {
try {
updateStatus(); //this function can change value of mInterval.
} finally {
// 100% guarantee that this always happens, even if
// your update method throws an exception
mHandler.postDelayed(mStatusChecker, mInterval);
}
}
};
void startRepeatingTask() {
mStatusChecker.run();
}
void stopRepeatingTask() {
mHandler.removeCallbacks(mStatusChecker);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment