一、服务端
AndroidManifest.xml中添加服务
<serviceandroid:name=".MyMessengerService"android:enabled="true"android:exported="true" ><intent-filter><action android:name="${applicationId}.MyMessengerService" /></intent-filter></service>
添加服务类
package com.example.aidlservice;import android.app.Service;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;import androidx.annotation.NonNull;
import androidx.annotation.Nullable;import com.example.aidlservice.util.L;import java.util.ArrayList;
import java.util.List;/*** @author Liushihua* @date 2022-5-12 9:24* @desc*/
public class MyMessengerService extends Service {static final String TAG = "MyMessengerService";static final int MSG_FROM_CLIENT = 1;private Messenger messenger;private static List<Messenger> clients = new ArrayList<>();@Nullable@Overridepublic IBinder onBind(Intent intent) {L.d("onBind");messenger = new Messenger(new MessengerHandler());return messenger.getBinder();}static class MessengerHandler extends Handler {@Overridepublic void handleMessage(@NonNull Message msg) {switch (msg.what) {case MSG_FROM_CLIENT:L.d("收到客户端消息:" + msg.getData().get("name"));if (msg.replyTo != null) {//获取客户端发来得messengerclients.add(msg.replyTo);try {Message sendMsg = Message.obtain(null, 2, 0, 0);Bundle bundle = new Bundle();bundle.putString("name", "小李子你好");sendMsg.setData(bundle);msg.replyTo.send(sendMsg);} catch (RemoteException e) {//客户端已断开e.printStackTrace();clients.remove(msg.replyTo);//移除此客户端}}break;default:super.handleMessage(msg);}}}@Overridepublic boolean onUnbind(Intent intent) {L.d("onUnbind");return super.onUnbind(intent);}@Overridepublic void onDestroy() {L.d("onDestroy");super.onDestroy();}
}
二、客户端
Activity中代码段
private Messenger messenger = null;//服务端messengerprivate boolean bound;//是否已连接服务端messengerprivate final Handler handler = new Handler(Looper.myLooper()) {@Overridepublic void handleMessage(@NonNull Message msg) {super.handleMessage(msg);L.d("收到服务端返回消息:" + msg.getData().getString("name"));}};/*** Class for interacting with the main interface of the service.*/private ServiceConnection messengerConnection = new ServiceConnection() {//for messengerpublic void onServiceConnected(ComponentName className, IBinder service) {// This is called when the connection with the service has been// established, giving us the object we can use to// interact with the service. We are communicating with the// service using a Messenger, so here we get a client-side// representation of that from the raw IBinder object.L.d("messengerConnection onServiceConnected");messenger = new Messenger(service);bound = true;}public void onServiceDisconnected(ComponentName className) {L.d("messengerConnection onServiceDisconnected");// This is called when the connection with the service has been// unexpectedly disconnected -- that is, its process crashed.messenger = null;bound = false;}};
findViewById(R.id.btnM).setOnClickListener(v -> {// Bind to the messengerServiceIntent intent = new Intent("com.example.aidlservice.MyMessengerService");//服务端定义的actionintent.setPackage("com.example.aidlservice");//服务端包名bindService(intent, messengerConnection, Context.BIND_AUTO_CREATE);});findViewById(R.id.btnMu).setOnClickListener(v -> {//解绑unbindService(messengerConnection);});findViewById(R.id.btnMS).setOnClickListener(v -> {//发送Messenger消息if (bound) {// Create and send a message to the service, using a supported 'what' valueMessage msg = Message.obtain(null, 1, 0, 0);// msg.obj="客户端消息";//不能这么用,发送不出去,报错:不是一个Parcelable数据Bundle bundle = new Bundle();bundle.putString("name", "小李子");msg.setData(bundle);try {msg.replyTo = new Messenger(handler);messenger.send(msg);} catch (RemoteException e) {e.printStackTrace();}}});