热门标签 | HotTags
当前位置:  开发笔记 > Android > 正文

AndroidMessenger实现进程间双向通信

简介 Messenger是安卓进程间通信 (IPC) 最为简单的方式,可以实现进程间双向通信。详见官网介绍 代码实现 服务端应用实现

简介

Messenger是安卓进程间通信 (IPC) 最为简单的方式,可以实现进程间双向通信。详见官网介绍

代码实现

服务端应用实现

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 CONFIG_NET = 1;
    private static final int CANCEL = 2;

    //发送给客户端的消息类型
    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;
                    break;
                case CANCEL:
                    Log.d("service", "cancel task");
                    mClient = msg.replyTo;
                    break;
                default:
                    break;
            }
        }
    }

    @Override
    public IBinder onBind(Intent intent) {
        Log.i("service", "service bind");
        return messenger.getBinder();
    }

    @Override
    public boolean onUnbind(Intent intent) {
        Log.i("service", "service unbind");
        mClient = null;
        return super.onUnbind(intent);
    }

 //向客户端发送消息
    public static void sendMessage() {
        if (null == mClient) {
            Log.d("service", "client is null");
            return;
        }
        try {
            Message message = Message.obtain(null, FIND_DEVICE);
            mClient.send(message);
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }
}

AndroidManifest.xml中注册messenger服务:


    
        
    

MainActivity中设置按钮用于向客户端主动发送消息:

package com.test.messengerservice;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {

    private Button button;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        button = findViewById(R.id.findDeviceButton);
        button.setOnClickListener( new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                MessengerService.sendMessage();
            }
        });
    }
}

客户端应用实现

MainActivity中绑定服务端的service,并设置向客户端发送消息的按钮:

package com.test.messengerclient;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
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 android.util.Log;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {

    // 服务端的Messenger
    private Messenger mService;
    // 客户端的Messenger
    private Messenger mMessenger;

    private Button buttonConfigNet;
    private Button buttonCancel;

    //发送给服务端的消息类型
    private static final int SEND_MESSENGER = 0;
    private static final int CONFIG_NET = 1;
    private static final int CANCEL = 2;

    //接收服务端的消息类型
    private static final int FIND_DEVICE = 10;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //客户端Messenger
        mMessenger = new Messenger(new ClientHandler());
        //绑定服务
        bindServiceInvoked();

  //设置点击事件
        buttOnConfigNet= findViewById(R.id.buttonConfigNet);
        buttOnCancel= findViewById(R.id.buttonCancel);
        
        buttonConfigNet.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(mService != null) {
                    try {
                        Log.d("client", "send config net");
                        Message message = Message.obtain(null, CONFIG_NET);
                        message.replyTo = mMessenger;
                        mService.send(message);
                    } catch (RemoteException e) {
                        e.printStackTrace();
                    }
                }
            }
        });

        buttonCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(mService != null) {
                    try {
                        Log.d("client", "send cancel");
                        Message message = Message.obtain(null, CANCEL);
                        message.replyTo = mMessenger;
                        mService.send(message);
                    } catch (RemoteException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
    }

 //接收服务连接和断开消息
    ServiceConnection serviceCOnnection= new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            Log.i("client", "service connected");
            mService = new Messenger(service);

   //由于绑定后服务端没有客户端的Messenger ,绑定后先将客户端Messenger发送给服务端
            if(mService != null) {
                try {
                    Log.d("client", "send messenger");
                    Message message = Message.obtain(null, SEND_MESSENGER);
                    message.replyTo = mMessenger;
                    mService.send(message);
                } catch (RemoteException e) {
                    e.printStackTrace();
                }
            }
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            Log.i("client", "service disconnected");
            mService = null;
        }
    };

 //从服务端接收消息
    public class ClientHandler extends Handler {

        @Override
        public void handleMessage(@NonNull Message msg) {
            switch (msg.what){
                case FIND_DEVICE:
                    Log.i("client", "find device");
                    break;
            }
        }
    }

 //绑定服务端的service
    private void bindServiceInvoked()
    {
        Intent intent = new Intent();
        intent.setAction("android.intent.action.MESSENGER");
        intent.setPackage("com.test.messengerservice");
        bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE);
    }
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。


推荐阅读
author-avatar
手机用户2502855967
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有