Skip to content

Instantly share code, notes, and snippets.

@MisterRager
Last active June 30, 2016 02:00
Show Gist options
  • Save MisterRager/92c28595b77c33164afbf0d4b0eec5da to your computer and use it in GitHub Desktop.
Save MisterRager/92c28595b77c33164afbf0d4b0eec5da to your computer and use it in GitHub Desktop.
A debounced IntentService
/*
* Copyright (c) 2016 PlanGrid, Inc. All rights reserved.
*/
package com.plangrid.android.services;
import android.app.IntentService;
import android.content.Intent;
import android.os.Bundle;
import com.plangrid.android.helpers.Logger;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
public abstract class DebounceIntentService extends IntentService{
public static final int DEBOUNCED = -1;
private final long mDebounceInterval;
private final AtomicBoolean mIsRunning = new AtomicBoolean(false);
private final String mServiceName;
public DebounceIntentService(String name, long time, TimeUnit type){
super(name);
mServiceName = name;
mDebounceInterval = type.toMillis(time);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId){
if(!mIsRunning.get()){
return super.onStartCommand(intent, flags, startId);
}
return DEBOUNCED;
}
@Override
protected void onHandleIntent(Intent intent){
try{
mIsRunning.set(true);
doWork(intent.getExtras());
wait(mDebounceInterval);
}catch(InterruptedException e){
Logger.getInstance().warning(mServiceName, "interrupted debounced intent");
}finally{
mIsRunning.set(false);
}
}
abstract void doWork(Bundle data);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment