messenger,client和server通信Demo

时间:2020-12-24 17:22:46
</pre><p>Server</p><p></p><p><pre name="code" class="java">public class MessengerService extends Service {

private Handler handle=new Handler(){
public void handleMessage(Message msg) {
//获得传过来的messenger,用来向客户端发送数据
Messenger replayTo=msg.replyTo;
//计算结果
int res=msg.arg1+msg.arg2;
//从消息池中获得一个新的message;
Message newMsg=Message.obtain();
//将计算的结果放到arg1中;
newMsg.arg1=res;

//newMsg.replyTo=replayTo;

try {
//发送回去给客户端
replayTo.send(newMsg);
} catch (RemoteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

};
};

@Override
public IBinder onBind(Intent intent) {
//绑定成功的时候打印一句
Toast.makeText(getApplicationContext(), "计算成功 ", 0).show();
//实质返回Messenger
//客户端发送的消息到上面处理
return new Messenger(handle).getBinder();
}



}


Client


public class MainActivity extends Activity implements OnClickListener {
private Button  bind;
private EditText num1,num2;
private TextView result;
private Messenger replyto;

/**
* 处理服务端返回的信息
*/
private Handler handle=new Handler(){
public void handleMessage(Message msg) {
result.setText(msg.arg1+"");

};
};
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

bind=(Button) findViewById(R.id.bind);
num1=(EditText) findViewById(R.id.num1);
num2=(EditText) findViewById(R.id.num2);
result=(TextView) findViewById(R.id.result);
//新建一个messenger,用于服务端返回数据的载体
replyto=new Messenger(handle);
bind.setOnClickListener(this);
}




@Override
public void onClick(View v) {

Intent intent=new Intent("ln");


bindService(intent, conn, Context.BIND_AUTO_CREATE);

}

private ServiceConnection conn=new ServiceConnection() {

@Override
public void onServiceDisconnected(ComponentName name) {
// TODO Auto-generated method stub

}

@Override
public void onServiceConnected(ComponentName name, IBinder service) {
//通过new messenger(Ibind )取得绑定返回的messenger。
Messenger messenger=new Messenger(service);
Message msg=Message.obtain();
msg.arg1=Integer.parseInt(num1.getText().toString());
msg.arg2=Integer.parseInt(num2.getText().toString());
//设置用于发送回来的messenger
msg.replyTo=replyto;
try {
messenger.send(msg);
} catch (RemoteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}
};



protected void onDestroy() {
unbindService(conn);

};