链接: https://github.com/jx0260/TestGradle
public class MessengerService extends Service {
private String TAG = "MessengerService";
private Handler mHandler = new Handler(Looper.getMainLooper()) {
@Override
public void handleMessage(@NonNull Message msg) {
super.handleMessage(msg);
Bundle data = msg.getData();
if (data.getInt("code") == 1) {
String objStr = data.getString("obj");
Log.i(TAG, "Server: receive " + objStr + " - is blue!");
Messenger clientMsger = msg.replyTo;
if (clientMsger != null) {
Message receiptMsg = new Message();
Bundle bundle = new Bundle();
bundle.putString("cont", "I'm server, I received: sky is blue.");
receiptMsg.setData(bundle);
try {
Log.i(TAG, "Server send back received msg.");
clientMsger.send(receiptMsg);
} catch (RemoteException e) {
e.printStackTrace();
}
}
}
}
};
@Nullable
@Override
public IBinder onBind(Intent intent) {
return new Messenger(mHandler).getBinder();
}
}
创建一个Service,MessengerService,声明 private Handler mHandler = new Handler 一个成员变量,此Handler用于处理来自客户端的请求。
在 onBind() 方法中,创建一个Messenger 对象(指定Handler)并返回给客户端。
配一下manifest.xml ( 注意 android:exported=“true”)
<service
android:name=".MessengerService"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="com.example.testgradle.MessengerService"/>
</intent-filter>
</service>
private Messenger mClientMessenger;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent messengerIntent = new Intent("com.example.testgradle.MessengerService");
messengerIntent.setPackage("com.example.testgradle");
bindService(messengerIntent, new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
mClientMessenger = new Messenger(service);
sendMessageToServer();
}
@Override
public void onServiceDisconnected(ComponentName name) {
}
}, BIND_AUTO_CREATE);
findViewById(R.id.btn_send_msg_to_server).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
sendMessageToServer();
}
});
}
private void sendMessageToServer() {
Log.i(TAG, "send msg to server...(sky)");
Message msg = Message.obtain();
Bundle bundle = new Bundle();
bundle.putString("obj", "sky");
bundle.putInt("code", 1);
msg.setData(bundle);
Log.i(TAG, "pass the client's Messenger to Server!");
msg.replyTo = new Messenger(mReceiveHandler);
try {
mClientMessenger.send(msg);
} catch (RemoteException e) {
e.printStackTrace();
}
}
在 onServiceConnected () 回调中,将IBinder 对象,重新封装成 Messenger。
在 sendMessageToServer() 方法中,构造 Message 传入数据,通过 mClientMessenger 发送出去。
注:此处构造的 Message msg = Message.obtain(); 在封装数据时,必须使用 Bundle,跨进程通信底层用的是 Parcelable 接口,而Bundle的实现如下:
public final class Bundle implements Parcelable
如果不使用Bundle,会报空Parcelable 的异常。
打印日志:
com.example.clientdemo I/ClientActivity: send msg to server...(sky)
com.example.clientdemo I/ClientActivity: pass the client's Messenger to Server!
com.example.testgradle I/MessengerService: Server: receive sky - is blue!
com.example.testgradle I/MessengerService: Server send back received msg.
com.example.clientdemo I/ClientActivity: Client received:I'm server, I received: sky is blue.
Log.i(TAG, "pass the client's Messenger to Server!");
msg.replyTo = new Messenger(mReceiveHandler);
我们在构造往服务端发送的Message时,向其中设置了一个 replyTo,其值为 new 一个Messenger,指定了一个在客户端创建的 mReceiveHandler 用来处理从服务端传来的消息:
private Handler mReceiveHandler = new Handler(Looper.getMainLooper()) {
@Override
public void handleMessage(@NonNull Message msg) {
super.handleMessage(msg);
Bundle data = msg.getData();
String cont = data.getString("cont");
Log.i(TAG, "Client received:" + cont);
}
};
简单说就是把一个客户端的 Messenger 传到了服务端,服务端使用此对象,向客户端回发数据。
Messenger clientMsger = msg.replyTo;
if (clientMsger != null) {
Message receiptMsg = new Message();
Bundle bundle = new Bundle();
bundle.putString("cont", "I'm server, I received: sky is blue.");
receiptMsg.setData(bundle);
try {
Log.i(TAG, "Server send back received msg.");
clientMsger.send(receiptMsg);
} catch (RemoteException e) {
e.printStackTrace();
}
}
注意,往客户端回发时,一样要使用Bundle。