Android开发使用开发使用Messenger及及Handler进行通信的方法示例进行通信的方法示例
本文实例讲述了Android开发使用Messenger及Handler进行通信的方法。分享给大家供大家参考,具体如下:
1. 客户端客户端service
public class MessageService extends Service {
private static final int MSG_SET_VALUE = 0x110;
private Handler mHandler = new Handler() {
public void handleMessage(Message msgFromClient) {
// 返回给客户的信息
Message msgToClient = Message.obtain(msgFromClient);
switch (msgFromClient.what) {
// msg 客户端传来的消息
case MSG_SET_VALUE:
try {
msgToClient.what = MSG_SET_VALUE;
SystemClock.sleep(2000);
msgToClient.arg2 = msgFromClient.arg1 + msgFromClient.arg2;
//msgFromClient.replyTo.send(msgToClient);
//得到客户端的信使对象,并向它发送消息
cMessenger = msgFromClient.replyTo;
cMessenger.send(msgToClient);
} catch (RemoteException e) {
e.printStackTrace();
}
break;
default:
break;
}
}
};
private Messenger mMessager = new Messenger(mHandler);
private Messenger cMessenger;
@Override
public IBinder onBind(Intent intent) {
return mMessager.getBinder();
}
@Override
public void onDestroy() {
cMessenger = null;
super.onDestroy();
}
}
2. 服务器端服务器端service
public class MessageService extends Service {
private static final int MSG_SET_VALUE = 0x110;
private Handler mHandler = new Handler() {
public void handleMessage(Message msgFromClient) {
// 返回给客户的信息
Message msgToClient = Message.obtain(msgFromClient);
switch (msgFromClient.what) {
// msg 客户端传来的消息
case MSG_SET_VALUE:
try {
msgToClient.what = MSG_SET_VALUE;
SystemClock.sleep(2000);
msgToClient.arg2 = msgFromClient.arg1 + msgFromClient.arg2;
//msgFromClient.replyTo.send(msgToClient);
//得到客户端的信使对象,并向它发送消息
cMessenger = msgFromClient.replyTo;
cMessenger.send(msgToClient);
} catch (RemoteException e) {
e.printStackTrace();
}
break;
default:
break;
}
}
};
private Messenger mMessager = new Messenger(mHandler);
private Messenger cMessenger;
@Override
public IBinder onBind(Intent intent) {
评论0
最新资源