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) {}
    }
}