栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Android Messenger跨进程双向传递消息(可传递bundle)

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Android Messenger跨进程双向传递消息(可传递bundle)

一、服务端

AndroidManifest.xml中添加服务


            
                
            
        

添加服务类

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;


public class MyMessengerService extends Service {
    static final String TAG = "MyMessengerService";
    static final int MSG_FROM_CLIENT = 1;
    private Messenger messenger;
    private static List 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"));
        }
    };

    
    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();
                }
            }
        });
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/881447.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号