Messenger
Reference to a Handler, which others can use to send messages to it. This allows for the implementation of message-based communication across processes, by creating a Messenger pointing to a Handler in one process, and handing that Messenger to another process.
Messenger的大概用法是:Server端通过service的onBind将messenger返回,Clien端拿到,通过Messenger的send就可以进行通信。
简单的用法如下:
Client端:
package main.xx.com.messager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
public class MainActivity extends AppCompatActivity {
private Messenger mClientMessenger = new Messenger(new Handler(){
@Override
public void handleMessage(Message msg) {
Log.i(Common.key,msg.getData().getString("key"));
super.handleMessage(msg);
}
});
private Messenger mServerMessagenger;
private ServiceConnection serviceConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
Log.i(Common.key,"onServiceConnected");
mServerMessagenger = new Messenger(service);
}
@Override
public void onServiceDisconnected(ComponentName name) {
mServerMessagenger = null;
};
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bindService(new Intent(MainActivity.this,MyService.class),serviceConnection, Context.BIND_AUTO_CREATE);
}
@Override
protected void onDestroy() {
super.onDestroy();
unbindService(serviceConnection);
}
public void click(View view){
Message message = Message.obtain();
Bundle bundle = new Bundle();
bundle.putString(Common.key,"这条消息来自客户端");
message.setData(bundle);
message.replyTo = mClientMessenger;
try {
mServerMessagenger.send(message);
} catch (RemoteException e) {
e.printStackTrace();
}
}
}
Server端:
package main.xx.com.messager;
import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.util.Log;
public class MyService extends Service {
Messenger messenger = new Messenger(new Handler(){
@Override
public void handleMessage(Message msg) {
Log.i(Common.key,"handleMessage");
Log.i(Common.key,msg.getData().getString(Common.key));
try {
msg.replyTo.send(msg);
} catch (RemoteException e) {
e.printStackTrace();
}
super.handleMessage(msg);
}
});
public MyService() {
}
@Override
public void onCreate() {
Log.i(Common.key,"oncreate");
super.onCreate();
}
@Override
public IBinder onBind(Intent intent) {
Log.i(Common.key,"onBind");
return messenger.getBinder();
}
}
源码链接: