Skip to content

Instantly share code, notes, and snippets.

@thinkerzhangyan
Created September 20, 2017 12:59
Show Gist options
  • Save thinkerzhangyan/eb752cfe5bd0ecc065785cce0f259794 to your computer and use it in GitHub Desktop.
Save thinkerzhangyan/eb752cfe5bd0ecc065785cce0f259794 to your computer and use it in GitHub Desktop.
MessengerService
public class MessengerService extends Service {
private static final String TAG = "MessengerService";
private static class MessengerHandler extends Handler {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case MyConstants.MSG_FROM_CLIENT:
Log.i(TAG, "receive msg from Client:" + msg.getData().getString("msg"));
Messenger client = msg.replyTo;
Message relpyMessage = Message.obtain(null, MyConstants.MSG_FROM_SERVICE);
Bundle bundle = new Bundle();
bundle.putString("reply", "嗯,你的消息我已经收到,稍后会回复你。");
relpyMessage.setData(bundle);
try {
client.send(relpyMessage);
} catch (RemoteException e) {
e.printStackTrace();
}
break;
default:
super.handleMessage(msg);
}
}
}
private final Messenger mMessenger = new Messenger(new MessengerHandler());
@Override
public IBinder onBind(Intent intent) {
return mMessenger.getBinder();
}
@Override
public void onCreate() {
super.onCreate();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
return super.onStartCommand(intent, flags, startId);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment