Last active
April 4, 2022 23:07
-
-
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
This file contains hidden or 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
/* | |
* 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