Skip to content

Instantly share code, notes, and snippets.

@Anrimian
Created November 5, 2017 16:24
Show Gist options
  • Save Anrimian/14a7ad216674c29daf22d26522dbf968 to your computer and use it in GitHub Desktop.
Save Anrimian/14a7ad216674c29daf22d26522dbf968 to your computer and use it in GitHub Desktop.
public class BoundServiceWrapper<T extends IBinder> {
private Context context;
private Class serviceClass;
private int serviceFlags;
private T binder;
private Action<T> deferAction;
public BoundServiceWrapper(Context context, Class serviceClass, int serviceFlags) {
this.context = context;
this.serviceClass = serviceClass;
this.serviceFlags = serviceFlags;
}
public void call(Action<T> action) {
if (binder != null) {
action.call(binder);
} else {
deferAction = action;
Intent intent = new Intent(context, serviceClass);
context.bindService(intent, serviceConnection, serviceFlags);
}
}
private ServiceConnection serviceConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName className, IBinder iBinder) {
//noinspection unchecked
binder = (T) iBinder;
if (deferAction != null) {
deferAction.call(binder);
deferAction = null;
}
}
@Override
public void onServiceDisconnected(ComponentName arg0) {
binder = null;
}
};
public interface Action<T extends IBinder> {
void call(T binder);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment