Created
December 26, 2019 14:51
-
-
Save israteneda/0ba1b449b2f901fef0fd78fefa5e27d6 to your computer and use it in GitHub Desktop.
Repeating task with handler
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
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