笔记36 | android通讯之实现一个Messenger通讯例子

地址:

笔记36 | android通讯之实现一个Messenger通讯例子


前言:

Android进程间的通信方式常见有Intent,Broadcast,aidl,SharedPreferences,ContentProvider,Messenger,Socket。
本节要学习的就是Messenger!


目录

  • Messenger介绍
  • 实现

Messenger介绍

/**
 * Reference to a Handler, which others can use to send messages to it(引用一个Handler,其他人可以用来向它发送消息).
 * This allows for the implementation of message-based communication across
 * processes(这允许实现基于消息的通信的实现), by creating a Messenger pointing to a Handler in one process(通过在一个进程中创建一个指向处理程序的Messenger),
 * and handing that Messenger to another process(将Messenger交给另一个进程).
 */
public final class Messenger implements Parcelable {

通讯流程

服务端提供一个Service来处理客户端连接,维护一个Handler来创建Messenger,在onBind时返回Messenger的binder。
双方用Messenger来发送数据,用Handler来处理数据。Messenger处理数据依靠Handler,所以是串行的,也就是说,Handler接到多个message时,就要排队依次处理。


实现

A.Service端:

服务端就一个Service,先去声明一个Messenger对象,然后onBind方法返回mMessenger.getBinder();

然后坐等客户端将消息发送到handleMessage想法,根据message.what去判断进行什么操作,然后做对应的操作,最终将结果通过 msgfromClient.replyTo.send(msgToClient);返回。

这里主要是取出客户端传来的两个数字,然后求和返回,这里我有意添加了sleep(1500)模拟耗时,注意在实际使用过程中,可以换成在独立开辟的线程中完成耗时操作,比如和HandlerThread结合使用。

/*
 * Service端,负责接收并处理Messenger数据并返回结果给Client端
 * evan by 20171117
 */
public class mService extends Service{

    @Override
    public IBinder onBind(Intent intent) {
        return messenger.getBinder();
    }

    private static final int MSG_SUM = 0x110;
    private Messenger messenger = new Messenger(new Handler(){//声明一个messenger对象

        public void handleMessage(Message frommsg) {

            Message tomessage = Message.obtain(frommsg);
            switch (frommsg.what) {//判断做什么操作
            case MSG_SUM:
                tomessage.what=MSG_SUM;
                try {
                    Thread.sleep(1500);
                    tomessage.arg1 = frommsg.arg1+frommsg.arg2;
                    frommsg.replyTo.send(tomessage);//返回数据
                    Log.i("md", "收到aig1:"+frommsg.arg1+", aig2:"+frommsg.arg2+", what:"+frommsg.what+", 并返回了:"+tomessage.arg1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                    Toast.makeText(getApplication(), "e.InterruptedException()", 1).show();
                    } catch (RemoteException e) {
                    e.printStackTrace();
                    Toast.makeText(getApplication(), "e.RemoteException()", 1).show();
                }
                break;
            }
            super.handleMessage(frommsg);
        };
    });
}
B.AndroidManifest中注册service
 <service 
            android:name=".mService"
            android:enabled="true"
            android:exported="true">
            <intent-filter>
                <action android:name="com.evan.messer"></action>
                <category android:name="android.intent.category.DEFAULT"/>
                </intent-filter>
            </service>
C.Client端:

首先建立连接:写一个bindService的方法bindServiceInvoike(),在onServiceConnected中拿到回调的service(IBinder)对象,通过service对象去构造一个mService =new Messenger(service);

建立连接后,就可以使用mService.send(msg)给服务端了。

发送后,在写一个接受service返回的方法messenger,service收到消息后,处理完成会将结果返回,就可以传到Client端的messenger中的Handler的handleMessage方法中了。

/*
 * Client端,负责通过Messenger发送与接受数据
 * evan by 20171117
 */
public class MainActivity extends ActionBarActivity implements OnClickListener{
    private static final String TAG = "MainActivity";
    private static final int MSG_SUM = 0x110;

    private Button mBtnAdd;
    private LinearLayout mLyContainer;
    //显示连接状态
    private TextView mTvState,mTvInfo;

    private Messenger mService;
    private boolean isConn;

    private int mA;

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

    private void initView() {
        mTvState=(TextView)findViewById(R.id.textView1);
        mLyContainer=(LinearLayout)findViewById(R.id.mLyContainer);
        mBtnAdd=(Button)findViewById(R.id.button1);
        mBtnAdd.setOnClickListener(this);
    }

    /*
     * 建立连接
     */
    private void bindServiceInvoike() {
        Intent intent = new Intent();
        intent.setAction("com.evan.messer");
        bindService(intent, mConn, Context.BIND_AUTO_CREATE);
    }

        /*
     * 拿到ServiceConnection连接数据
     */
    private ServiceConnection mConn = new ServiceConnection() {

        @Override
        public void onServiceDisconnected(ComponentName name) {
            mService = null;
            isConn = false;
            mTvState.setText("disconnected!");
        }

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            mService = new Messenger(service);
            isConn = true;
            mTvState.setText("connected!");
        }
    };

    /*
     * 发送消息
     */
    @Override
    public void onClick(View v) {
        try {
            int a = mA++;
            int b = (int)(Math.random()*100);

            TextView tv = new TextView(MainActivity.this);
            tv.setText(a+"+"+b+" = 服务器返回的结果: ");
            tv.setId(b);
            mLyContainer.addView(tv);

            Message msgFromClient = Message.obtain(null,MSG_SUM,a,b);
            msgFromClient.replyTo = messenger;

            if (isConn) {
                mService.send(msgFromClient);//往服务里发信息
                Log.i("md", "发送aig1:"+a+", aig2:"+b+",what:"+MSG_SUM+",给services!");
            }

        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }

        /*
     * 接收service处理的数据
     */
    private Messenger messenger = new Messenger(new Handler(){//服务端会收到消息,处理完成会将结果返回,

        public void handleMessage(Message msgfrom) {
            switch (msgfrom.what) {
            case MSG_SUM:
                  TextView tv = (TextView) mLyContainer.findViewById(msgfrom.arg2);
                  tv.setText(tv.getText() + " = " + msgfrom.arg1);
                  Log.i("md", "收到service的Messenger数据:"+msgfrom.arg1);
                  break;
            }
            super.handleMessage(msgfrom);
        };
    });

        /*
         *断开与服务器的连接
         */
    protected void onDestroy() {
        super.onDestroy();
        unbindService(mConn);
    };
}
D.XML:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/mLyContainer"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.messenger_client.MainActivity"
    tools:ignore="MergeRootFrame"
    android:orientation="vertical"
     >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="状态信息:"
        />

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="发送" 
        />

</LinearLayout>

E.运行:

运行效果
打印:

01-01 00:08:35.045: I/md(1693): 收到service的Messenger数据:6
01-01 00:08:36.544: I/md(1740): 收到aig1:2, aig2:99, what:272, 并返回了:101
01-01 00:08:36.545: I/md(1693): 收到service的Messenger数据:101

转载于:https://www.cnblogs.com/xiangevan/p/10751681.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值