Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@jkpark
Created March 22, 2017 14:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jkpark/938cc27168d28bdc5bc17e9230d780d3 to your computer and use it in GitHub Desktop.
Save jkpark/938cc27168d28bdc5bc17e9230d780d3 to your computer and use it in GitHub Desktop.
Binding Service - Activity
Messenger mService = null;
boolean bindService = false;
class IncomingHandler extends Handler {
@Override
public void handleMessage(Message msg) {
}
}
final Messenger mMessenger = new Messenger(new IncomingHandler());
private ServiceConnection mConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder service) {
mService = new Messenger(service);
try {
Message msg = Message.obtain(null, MessengerService.MSG_REGISTER_CLIENT);
msg.replyTo = mMessenger;
mService.send(msg);
} catch (RemoteException e) {
}
}
public void onServiceDisconnected(ComponentName className) {
mService = null;
}
};
void doBindService() {
// Establish a connection with the service. We use an explicit
// class name because there is no reason to be able to let other
// applications replace our component.
bindService = getApplicationContext().bindService(new Intent(mActivity.this, MessengerService.class), mConnection, Context.BIND_AUTO_CREATE);
}
void doUnbindService() {
if (bindService) {
// If we have received the service, and hence registered with it, then now is the time to unregister.
if (mService != null) {
try {
Message msg = Message.obtain(null, MessengerService.MSG_UNREGISTER_CLIENT);
msg.replyTo = mMessenger;
mService.send(msg);
} catch (RemoteException e) {
// There is nothing special we need to do if the service has crashed.
}
}
// Detach our existing connection.
getApplicationContext().unbindService(mConnection);
bindService = false;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment