[Android]IPC通信之Messenger的使用方法介绍

本文介绍了Messenger作为Android进程间通信的一种轻量级方案,利用Handler和IBinder实现远程通信。通过实例演示了Server与Client如何通过Messenger发送和接收Message。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

github地址:https://github.com/lixiang0/DemoLibs

Messenger(信使)是一种轻量级的IPC(Inter-Process Communication)实现方案,它的底层实现是AIDL(Android Interface Definition Language)。具体的应用中涉及到的类包括:Messenger和Message。
Messenger类的源代码如下:

package android.os;

public final class Messenger implements Parcelable {
   public Messenger(Handler target) { throw new RuntimeException("Stub!"); }
   public Messenger(IBinder target) { throw new RuntimeException("Stub!"); }
   public void send(Message message) throws RemoteException { throw new RuntimeException("Stub!"); }
   public IBinder getBinder() { throw new RuntimeException("Stub!"); }
   public boolean equals(Object otherObj) { throw new RuntimeException("Stub!"); }
   public int hashCode() { throw new RuntimeException("Stub!"); }
   public int describeContents() { throw new RuntimeException("Stub!"); }
   public void writeToParcel(Parcel out, int flags) { throw new RuntimeException("Stub!"); }
   public static void writeMessengerOrNullToParcel(Messenger messenger, Parcel out) { throw new RuntimeException("Stub!"); }
   public static Messenger readMessengerOrNullFromParcel(Parcel in) { throw new RuntimeException("Stub!"); }
   public static final Parcelable.Creator<Messenger> CREATOR = null;
}

从Messenger的源码可以看到它有2个构造方法:

   public Messenger(Handler target) { throw new RuntimeException("Stub!"); }
   public Messenger(IBinder target) { throw new RuntimeException("Stub!"); }

我们可以通过传入一个Handler或者一个IBinder对象获取到远程Messenger,并且Messenger对象本身也可以返回IBinder对象供外部调用。

public IBinder getBinder() { throw new RuntimeException("Stub!"); }

Messenger发送Message对象的方法是:

   public void send(Message message) throws RemoteException { throw new RuntimeException("Stub!"); }

我们可以看到Messenger之间是通过Message来进行数据交换的。
下面我们将编写一个例子来学习Messenger的使用方法。
我们编写Server类用来接受Client的消息并返回消息。Server类的代码如下:

package string.pub.messenger.service;

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;

public class Server {
    private Messenger server=new Messenger(new Handler(new Handler.Callback() {

        @Override
        public boolean handleMessage(Message paramMessage) {
            // TODO Auto-generated method stub
            Log.d("123", paramMessage.getData().getString("msg"));
            Messenger mMessenger=paramMessage.replyTo;
            Message msg=new Message();
            Bundle mBundle=new Bundle();
            mBundle.putString("msg", "a value form server");
            msg.setData(mBundle);
            try {
                mMessenger.send(msg);
            } catch (RemoteException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            return true;
        }
    }));

    //向外暴露IBinder对象
    public IBinder getIBinder(){
        return server.getBinder();
    }
}

Client的代码如下:

package string.pub.messenger.client;

import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.util.Log;

public class Client {
    private Messenger client=new Messenger(new Handler(new Handler.Callback() {

        @Override
        public boolean handleMessage(Message paramMessage) {
            // TODO Auto-generated method stub
            Log.d("123", paramMessage.getData().getString("msg"));
            return true;
        }
    }));

    //向外暴露IBinder对象
    public IBinder getIBinder(){
        return client.getBinder();
    }
}

Server和Client的类图如下:

这里写图片描述

他们都是通过Handler对象构造一个Messenger对象,并且将自己的IBinder对象暴露给外界使用。
Server类的功能是接受Client的消息之后返回一个消息(“a value from server”)。
Client类的功能是发送一个消息(“a value from client”)到Server类。

主Activity类的代码如下:

package string.pub.messenger;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import string.pub.messenger.client.Client;
import string.pub.messenger.service.Server;

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        LinearLayout mLinearLayout=(LinearLayout) this.getLayoutInflater().inflate(R.layout.activity_main,null);
        final Client client=new Client();
        final Server server=new Server();
        Button mButton=new Button(this);
        final TextView mTextView=new TextView(this);
        mButton.setText("click to send msg");
        mButton.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                Message msg=new Message();
                //设置消息回复的对象是Client
                msg.replyTo=new Messenger(client.getIBinder());
                Bundle mBundle=new Bundle();
                mBundle.putString("msg", "a value form client");
                Log.d("123", "onClick");
                msg.setData(mBundle);
                try {
                //通过getIBinder()来得到Server对象
                    new Messenger(server.getIBinder()).send(msg);
                } catch (RemoteException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        });
        mLinearLayout.addView(mButton,0);
        mLinearLayout.addView(mTextView,1);
        setContentView(mLinearLayout);
    }
}

界面代码如下:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/LinearLayout1"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="${relativePackage}.${activityClass}" >

</LinearLayout>

本程序运行结果如下:
这里写图片描述

可以看到以上已经实现了Messenger的使用以及Messenger之间的通信了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值