Skip to content

Instantly share code, notes, and snippets.

@eric-romero
Last active June 17, 2019 17:04
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 eric-romero/9d8bc1ac18ee1a3c7946551ffe143851 to your computer and use it in GitHub Desktop.
Save eric-romero/9d8bc1ac18ee1a3c7946551ffe143851 to your computer and use it in GitHub Desktop.
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