Skip to content

Instantly share code, notes, and snippets.

@jkpark
Created March 22, 2017 14:53
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/4e9d1a9489113dba7970c07d3b1ab7a1 to your computer and use it in GitHub Desktop.
Save jkpark/4e9d1a9489113dba7970c07d3b1ab7a1 to your computer and use it in GitHub Desktop.
Binding Service - Service
/**
* Command to the service to register a client, receiving callbacks
* from the service. The Message's replyTo field must be a Messenger of
* the client where callbacks should be sent.
*/
public final static int MSG_REGISTER_CLIENT = 1;
/**
* Command to the service to unregister a client, ot stop receiving callbacks
* from the service. The Message's replyTo field must be a Messenger of
* the client as previously given with MSG_REGISTER_CLIENT.
*/
public final static int MSG_UNREGISTER_CLIENT = 2;
/**
* Command to service to set a new value. This can be sent to the
* service to supply a new value, and will be sent by the service to
* any registered clients with the new value.
*/
static final int MSG_SET_VALUE = 3;
ArrayList<Messenger> mClients = new ArrayList<Messenger>();
private final Messenger mMessenger = new Messenger(new IncomingHandler());
private class IncomingHandler extends Handler {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case MSG_REGISTER_CLIENT:
mClients.add(msg.replyTo);
break;
case MSG_UNREGISTER_CLIENT:
mClients.remove(msg.replyTo);
break;
}
}
}
@Override
public IBinder onBind(Intent intent) {
return mMessenger.getBinder();
}
/**
* Send Message to Clients.
* @param msg Message
*/
private void sendMessageToClients(Message msg) {
for (int i = mClients.size() - 1; i >= 0; i--) {
try {
// send a message to mClients.
// you may have handle this massage from IncomingHandler at any Activity
mClients.get(i).send(msg);
} catch (RemoteException e) {
// The client is dead. Remove it from the list;
// we are going through the list from back to front
// so this is safe to do inside the loop.
mClients.remove(i);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment