Created
November 5, 2017 16:24
-
-
Save Anrimian/14a7ad216674c29daf22d26522dbf968 to your computer and use it in GitHub Desktop.
This file contains 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 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