Last active
August 29, 2015 14:02
-
-
Save frenchie4111/6086c6e4327d7936364a to your computer and use it in GitHub Desktop.
Android service binding
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 abstract class BindableService extends Service | |
{ | |
LocalBinder binder = new LocalBinder(); | |
public class LocalBinder extends Binder { | |
Service getService() { | |
// Return this instance of LocalService so clients can call public methods | |
return BindableService.this; | |
} | |
}; | |
@Override | |
public IBinder onBind(Intent intent) { | |
return binder; | |
} | |
} |
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 abstract class BindingFragment extends Fragment { | |
// serviceClass is the type of class bound to, should be set in inherting's onCreate or onCreateView | |
Class<? extends BindableService> serviceClass; | |
// service will eventually hold the bound to service | |
Service service = null; | |
public boolean bound; | |
@Override | |
public void onStart() { | |
super.onStart(); | |
// Binds to service here, if you want the service to run independent of this bind, make | |
// sure you also start it with startService and START_STICKY | |
Intent serviceIntent = new Intent( getActivity().getApplicationContext(), serviceClass ); | |
getActivity().bindService(serviceIntent, serviceConnection, Context.BIND_AUTO_CREATE); | |
} | |
@Override | |
public void onStop() { | |
super.onStop(); | |
if (bound) { | |
bound = false; | |
// Make sure we tell the service we don't need it anymore | |
getActivity().unbindService( serviceConnection ); | |
} | |
} | |
public abstract void onServiceConnected(); | |
private ServiceConnection serviceConnection = new ServiceConnection() { | |
@Override | |
public void onServiceConnected(ComponentName className, IBinder serviceBind) { | |
// We've bound to LocalService, cast the IBinder and get LocalService instance | |
LocalBinder binder = (LocalBinder)serviceBind; | |
service = binder.getService(); | |
bound = true; | |
BindingFragment.this.onServiceConnected(); | |
} | |
@Override | |
public void onServiceDisconnected(ComponentName arg0) { | |
bound = false; | |
} | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment