一、服务端
AndroidManifest.xml中添加服务
<service
android: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
@Override
public IBinder onBind(Intent intent) {
L.d("onBind");
messenger = new Messenger(new MessengerHandler());
return messenger.getBinder();
}
static class MessengerHandler extends Handler {
@Override
public void handleMessage(@NonNull Message msg) {
switch (msg.what) {
case MSG_FROM_CLIENT:
L.d("收到客户端消息:" + msg.getData().get("name"));
if (msg.replyTo != null) {//获取客户端发来得messenger
clients.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);
}
}
}
@Override
public boolean onUnbind(Intent intent) {
L.d("onUnbind");
return super.onUnbind(intent);
}
@Override
public void onDestroy() {
L.d("onDestroy");
super.onDestroy();
}
}
二、客户端
Activity中代码段
private Messenger messenger = null;//服务端messenger
private boolean bound;//是否已连接服务端messenger
private final Handler handler = new Handler(Looper.myLooper()) {
@Override
public 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 messenger
public 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 messengerService
Intent intent = new Intent("com.example.aidlservice.MyMessengerService");//服务端定义的action
intent.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' value
Message 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();
}
}
});
|