Skip to content

Instantly share code, notes, and snippets.

@logcat
Created December 27, 2016 14:33
Show Gist options
  • Save logcat/e2037d54e6d452336e642c205f3fd433 to your computer and use it in GitHub Desktop.
Save logcat/e2037d54e6d452336e642c205f3fd433 to your computer and use it in GitHub Desktop.
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import java.util.concurrent.CountDownLatch;
public class ServiceConnector<T> {
private static final String TAG = ServiceConnector.class.getSimpleName();
private T service;
CountDownLatch latch = new CountDownLatch(0);
private ServiceConnection serviceConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
LOG.d(TAG + ".onServiceConnected for " + serviceIntent);
ServiceConnector.this.service = serviceFactory.call(service);
latch.countDown();
}
@Override
public void onServiceDisconnected(ComponentName name) {
LOG.d(TAG + ".onServiceDisconnected for " + serviceIntent);
latch.countDown();
ServiceConnector.this.service = null;
}
};
private Intent serviceIntent;
private Func1<IBinder, T> serviceFactory;
public ServiceConnector(Intent serviceIntent, Func1<IBinder, T> serviceFactory) {
this.serviceIntent = serviceIntent;
this.serviceFactory = serviceFactory;
}
/**
* This is blocking call!!!
* <p/>
* Should only be called from background thread.
*
* @return service
*/
public T getService(Context context) {
if (service == null) {
try {
latch = new CountDownLatch(1);
LOG.d(TAG + ".onCreate bind service " + serviceConnection);
context.bindService(serviceIntent, serviceConnection, Context.BIND_AUTO_CREATE);
latch.await();
} catch (InterruptedException e) {
LOG.e(TAG + ".getService() - interrupted error");
}
}
return service;
}
public void unbindService(Context context) {
context.unbindService(serviceConnection);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment