码迷,mamicode.com
首页 > 移动开发 > 详细

android进程通信之Messenger

时间:2015-08-15 16:40:03      阅读:143      评论:0      收藏:0      [点我收藏+]

标签:messenger   android   

写在前面的话

前面我写了一篇文章—android学习之remote service 的aidl详解,讲到跨进程多线程通信,我们使用aidl技术来实现。但是平时我们可能只要要求跨进程通信,而不需要使用多线程,那么这时候,Messenger就是我们的一个非常好的选择。

Messenger实例

Server端:

MessengerService.java

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 android.widget.Toast;

public class MessengerService extends Service {

    public static final String TAG = "MessengerService";

    public static final int MSG_SEND_TO_SERVER = 1;
    public static final int MSG__REPLY_FROM_SERVER = 2;

    final Messenger mMessenger = new Messenger(new IncomingHandler());

    class IncomingHandler extends Handler {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_SEND_TO_SERVER:
                    Log.i(TAG, "MSG_SEND_TO_SERVER:"+"--msg.arg1:"+msg.arg1+"--msg.arg2:"+msg.arg2);
                    try {
                        Message messageReplyToClient = new Message();
                        messageReplyToClient.what = MSG__REPLY_FROM_SERVER;
                        messageReplyToClient.arg1 = msg.arg2;
                        messageReplyToClient.arg2 = msg.arg1;
                        msg.replyTo.send(messageReplyToClient);
                    } catch (RemoteException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }               
                    break;
                default:
                    super.handleMessage(msg);
            }
        }
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO Auto-generated method stub
        Toast.makeText(getApplicationContext(), "binding", Toast.LENGTH_SHORT).show();
        return mMessenger.getBinder();
    }
}

Client端

MainActivity.java

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;
import android.widget.TextView;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;

public class MainActivity extends Activity {

    public static final String TAG = "MainActivity";
    public static final int MSG_SEND_TO_SERVER = 1;
    public static final int MSG__REPLY_FROM_SERVER = 2;      
    private Messenger mMessenger;
    boolean mBound;
    private TextView textViewShowConnectState;
    private TextView textViewMessageSendToService;
    private TextView textViewMessageReceiverFromService;
    private Button button;

    private Messenger mMessengerReceive = new Messenger(new MyHandler());
    class MyHandler extends Handler {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG__REPLY_FROM_SERVER:
                    Log.i(TAG, "MSG__REPLY_FROM_SERVER:"+"--msg.arg1="+msg.arg1+"--msg.arg2="+msg.arg2);
                    textViewMessageReceiverFromService.setText("msg:server-->client:"+"--msg.arg1="+msg.arg1+"--msg.arg2="+msg.arg2);
                    break;
                default:
                    super.handleMessage(msg);
            }
        }
    }

    private ServiceConnection mConnection = new ServiceConnection() {
        public void onServiceConnected(ComponentName className, IBinder service) {
            mMessenger = new Messenger(service);
            mBound = true;
            textViewShowConnectState.setText("service connect");            
        }

        public void onServiceDisconnected(ComponentName className) {
            mMessenger = null;
            mBound = false;
            textViewShowConnectState.setText("service disconnect");
        }
    };

    public void sendMessage(View v) {
        if (!mBound) return;
        // Create and send a message to the service, using a supported ‘what‘ value
        int arg1 = (int) (Math.random() * 100);;
        int arg2 = (int) (Math.random() * 100);;
        Message msg = Message.obtain(null, MSG_SEND_TO_SERVER, arg1, arg2);
        msg.replyTo = mMessengerReceive;
        textViewMessageSendToService.setText("msg:client-->server:"+"--msg.arg1="+msg.arg1+"--msg.arg2="+msg.arg2);
        try {
            mMessenger.send(msg);
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }

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

    private void init() {
        // TODO Auto-generated method stub  
        textViewShowConnectState = (TextView)findViewById(R.id.textViewShowConnectState);
        textViewMessageSendToService = (TextView)findViewById(R.id.textViewMessageSendToService);
        textViewMessageReceiverFromService = (TextView)findViewById(R.id.textViewMessageReceiverFromService);
        button = (Button)findViewById(R.id.button);
    }

    @Override
    protected void onStart() {
        super.onStart();
        bindService(new Intent("com.android.ACTION.MessengerService"), mConnection,
            Context.BIND_AUTO_CREATE);
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (mBound) {
            unbindService(mConnection);
            mBound = false;
        }
    }

}

我们Client给Server发送消息的是封装在sendMessage方法中的:

mMessenger.send(msg);

那么如何响应从server端回传的消息了,这中间的关键是把client发送到server的消息msg与回调处理的Messenger mMessengerReceive相关联:

msg.replyTo = mMessengerReceive;

布局文件:

activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <TextView
        android:id="@+id/textViewShowConnectState"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        />

    <Button 
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/textViewShowConnectState"
        android:onClick="sendMessage"      
        android:text="click send message to Server"  
        />

    <TextView
        android:id="@+id/textViewMessageSendToService"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/button"/>

    <TextView
        android:id="@+id/textViewMessageReceiverFromService"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/textViewMessageSendToService"/>

</RelativeLayout>

效果图

从源码和效果图,我们可以看出,这个Demo是从Client发送一个消息到Server,Server把消息的msg.arg1和msg.arg2的值交换后再反馈给Client,Client将从Client发送到Server的消息和Server返回的消息都显示出来。

版权声明:本文为博主原创文章,未经博主允许不得转载。

android进程通信之Messenger

标签:messenger   android   

原文地址:http://blog.csdn.net/hfreeman2008/article/details/47322565

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!