Skip to content

Instantly share code, notes, and snippets.

@franciscomxs
Created December 15, 2015 17:28
Show Gist options
  • Save franciscomxs/8435da683ad5572e8a71 to your computer and use it in GitHub Desktop.
Save franciscomxs/8435da683ad5572e8a71 to your computer and use it in GitHub Desktop.
Android - Binding Service to Activity
// ...
private MyService myService;
private boolean messengerBound = false;
@Override
protected void onStart() {
super.onStart();
Intent intent = new Intent(this, PlayerService.class);
bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE);
}
@Override
protected void onPause() {
LocalBroadcastManager.getInstance(this).unregisterReceiver(broadcastReceiver);
super.onPause();
}
@Override
protected void onDestroy() {
super.onDestroy();
unbindService(serviceConnection);
messengerBound = false;
}
private ServiceConnection serviceConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
PlayerService.LocalBinder binder = (PlayerService.LocalBinder) service;
playerService = binder.getService();
messengerBound = true;
}
@Override
public void onServiceDisconnected(ComponentName name) {
messengerBound = false;
}
};
// ...
// ...
private final IBinder binder = new LocalBinder();
public class LocalBinder extends Binder {
public PlayerService getService(){
return PlayerService.this;
}
}
@Override
public IBinder onBind(Intent intent) {
return binder;
}
// ...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment