Skip to content

Instantly share code, notes, and snippets.

@hiq-larryschiefer
Last active April 4, 2022 23:07
Show Gist options
  • Save hiq-larryschiefer/942c73f3064cfc2a37cb to your computer and use it in GitHub Desktop.
Save hiq-larryschiefer/942c73f3064cfc2a37cb to your computer and use it in GitHub Desktop.
Example of an Android Service using a periodic Runnable on a simple background thread
/*
* Example code to help with Stack Overflow post:
* http://stackoverflow.com/questions/35843374/android-pausing-service-thread-asynctask-using-a-handler-with-postdelayed-for
*
* THIS IS JUST SAMPLE CODE, HAS NOT BEEN BUILT OR TESTED.
*/
public class MyService extends Service {
protected static final DEFAULT_TIMEOUT = 5000;
protected static final EXTENDED_TIMEOUT = 20000;
private HandlerThread mBgThread;
private Handler mBgHandler;
private MyTimerRunnable mRunnable;
@Override
public void onCreate() {
mBgThread = new HandlerThread("MyBgThread");
mBgThread.start();
mBgHandler = new mBgHandler(mBgThread.getLooper(), this);
mRunnable = new MyTimerRunnable();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
mBgHandler.removeCallbacks(mRunnable);
mBgHandler.postDelayed(mRunnable, EXTENDED_TIMEOUT);
return START_STICKY;
}
@Override
public void onDestroy() {
mBgHandler.removeCallbacks(mRunnable);
mBgThread.quitSafely();
}
private class MyTimerRunnable implements Runnable {
@Override
public void run() {
// Do whatever work you need
// Reschedule the Runnable
mBgHandler.postDelayed(this, DEFAULT_TIMEOUT);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment