Last active
June 17, 2019 17:04
-
-
Save eric-romero/9d8bc1ac18ee1a3c7946551ffe143851 to your computer and use it in GitHub Desktop.
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
public class BackgroundJobService extends JobIntentService { | |
public static final int JOB_ID = 1000; | |
public static volatile boolean shouldContinue = false; | |
private static final Object lock = new Object(); | |
private static final long BACKGROUND_TIMEOUT_WAIT_MS = 5000; | |
final Handler mHandler = new Handler(); | |
public static void enqueueWork(Context context) { | |
Intent bgJobService = new Intent(context, BackgroundJobService.class); | |
BackgroundJobService.enqueueWork( | |
context, BackgroundJobService.class, BackgroundJobService.JOB_ID, bgJobService); | |
} | |
public static void stopWork() { | |
synchronized (lock) { | |
shouldContinue = false; | |
lock.notifyAll(); | |
} | |
} | |
@Override | |
protected void onHandleWork(@NonNull Intent intent) { | |
shouldContinue = true; | |
try { | |
synchronized (lock) { | |
lock.wait(BACKGROUND_TIMEOUT_WAIT_MS); | |
if (shouldContinue) { | |
// Do the background work here | |
} | |
} | |
} catch (InterruptedException ex) {} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment