简介
Messenger是安卓进程间通信 (IPC) 最为简单的方式,可以实现进程间双向通信。详见官网介绍
https://developer.android.google.cn/guide/components/bound-services#Messenger
代码实现
服务端应用实现
MessengerService接收客户端发送的消息:
package com.test.messengerservice;
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;
import androidx.annotation.NonNull;
public class MessengerService extends Service {
//接收客户端的消息类型
private static final int SEND_MESSENGER = 0;
private static final int REQUEST_BIND_STATUS = 1;
private static final int CONFIG_NET = 2;
private static final int CANCEL = 3;
//发送给客户端的消息类型
private static final int FIND_DEVICE = 10;
public MessengerService() {
}
private Messenger messenger = new Messenger(new ServiceHandler());
private static Messenger mClient;
public class ServiceHandler extends Handler {
@Override
public void handleMessage(@NonNull Message msg) {
// 处理消息
switch(msg.what){
case SEND_MESSENGER:
Log.d("service", "receive messenger");
mClient = msg.replyTo;
break;
case CONFIG_NET:
Log.d("service", "config net task");
mClient = msg.replyTo;
String ssid = msg.getData().getString("ssid");
String pwd = msg.getData().getString("pwd");
Log.d(