Created
December 15, 2015 17:28
-
-
Save franciscomxs/8435da683ad5572e8a71 to your computer and use it in GitHub Desktop.
Android - Binding Service to Activity
This file contains hidden or 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
// ... | |
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; | |
} | |
}; | |
// ... |
This file contains hidden or 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
// ... | |
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