zoukankan      html  css  js  c++  java
  • Activity与Service使用Messenger通信

    参考:

    http://xwangly.iteye.com/blog/1109424
    

    Messenger介绍:

    Reference to a Handler, which others can use to send messages to it. This allows for the implementation of message-based communication across processes, by creating a Messenger pointing to a Handler in one process, and handing that Messenger to another process.

    大意为:它引用了一个Handler对象,以便others能够向它发送消息。该类允许跨进程间基于Message的通信(即两个进程间可以通过Message进行通信),在服务端使用Handler创建一个 Messenger,客户端持有这个Messenger就可以与服务端通信了。

    使用方法:

    1.服务端创建一个Messenger对象

           private Messenger mMessenger = new Messenger(mHandler);// 自己的信使对象

    2.(客户端)Activity绑定服务  bindService,服务返回一个binder,return mMessenger.getBinder();

    3. Activity利用返回的binder,创建一个信使rMessenger = new Messenger(service);

    4. Activity可以利用rMessenger向服务发送消息,rMessenger.send(msg),可以在msg中设置msg.replyTo = mMessenger(Activity的自身的信使);这样服务端也能得到客户端的Messenger,可利用这个Messenger向客户端发送消息。

    例子如下:

       客户端(MainActivity)向服务(MessengerService)发送查询时间的请求,服务端查询时间后,将时间返回给客户端。

    //MainActivity

    package com.example.servmessage;
    import android.app.Activity;
    import android.content.ComponentName;
    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.view.View.OnClickListener;
    import android.widget.Button;
    import android.widget.TextView;
    public class MainActivity extends Activity{
            private String TAG = "Binding";
            private Button bindButton,unbindButton,sendmsgButton;
            private TextView msgText;
            private boolean isBound;
            private Messenger mMessenger;//自己的信使
            private Messenger rMessenger; //远程服务的信使
            @Override
            protected void onCreate(Bundle savedInstanceState) {
                // TODO Auto-generated method stub
                super.onCreate(savedInstanceState);
                setContentView(R.layout.activity_main);
                bindButton=(Button)findViewById(R.id.bind);
                unbindButton=(Button)findViewById(R.id.unbind);
                sendmsgButton=(Button)findViewById(R.id.msg);
                msgText = (TextView) findViewById(R.id.callback);
                msgText.setText("未绑定.");
                //绑定
                bindButton.setOnClickListener(new OnClickListener() {
                    
                    @Override
                    public void onClick(View v) {
                        // TODO Auto-generated method stub
                        if (!isBound) {
                            Intent intent = new Intent(MainActivity.this,MessengerService.class);
                            startService(intent);
                            isBound = bindService(intent, connection, BIND_AUTO_CREATE);
                            msgText.setText("绑定成功");
                        }
                    }
                });
                //解绑定
                unbindButton.setOnClickListener(new OnClickListener() {
                    
                    @Override
                    public void onClick(View v) {
                        // TODO Auto-generated method stub
                        if (isBound) {
                            unbindService(connection);
                            isBound = false;
                            msgText.setText("已解除绑定");
                        }
                    }
                });
                //发送查询消息
                sendmsgButton.setOnClickListener(new OnClickListener() {
                    
                    @Override
                    public void onClick(View v) {
                        // TODO Auto-generated method stub
                        if(isBound)
                            sendMessage();
                    }
                });
    
            }
            private Handler mHandler = new Handler() {
                @Override
                public void handleMessage(Message msg) {
                    Log.i(TAG, "handleMessage");
                    switch (msg.what) {
                    case MessengerService.MSG_SET_TIME:
                        Bundle data=msg.getData();
                        String time=data.getString("time");
                        msgText.setText("current time: " +time);
                        break;
                    default:
                        super.handleMessage(msg);
                    }
                }
            };
            
            private ServiceConnection connection = new ServiceConnection() {
    
                public void onServiceConnected(ComponentName name, IBinder service) {
                    // TODO Auto-generated method stub
                    Log.i(TAG, "onServiceConnected");
                    rMessenger = new Messenger(service);
                    mMessenger = new Messenger(mHandler);            
                }
                public void onServiceDisconnected(ComponentName name) {
                    // TODO Auto-generated method stub
                    rMessenger = null;
                }
            };    
             // 使用服务端的信使向它发送一个消息。         
            private void sendMessage() {
                // TODO Auto-generated method stub
                Message message = Message.obtain(null, MessengerService.MSG_SET_TIME);
                message.replyTo = mMessenger;
                try {
                    rMessenger.send(message);
                } catch (RemoteException e) {
                    e.printStackTrace();
                }
            }
    
        }

    //MessengerService

    package com.example.servmessage;
    
    
    import java.text.SimpleDateFormat;
    import java.util.Calendar;
    import java.util.Random;
    
    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 android.util.Log;
    
    public class MessengerService extends Service {
        private String TAG = "MessengerService";
        private String DEFAULT_TIME_FORMAT = "yyyy-MM-dd hh:mm:ss";
        static final int MSG_SET_TIME = 1;
        private Handler mHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                // TODO Auto-generated method stub
                Log.i(TAG, "handleMessage");
                switch (msg.what) {
                case MSG_SET_TIME:
                    try {
                        Message message = Message.obtain(null,
                                MessengerService.MSG_SET_TIME);                    
                        SimpleDateFormat dateFormatter = new SimpleDateFormat(DEFAULT_TIME_FORMAT);  
                       String time = dateFormatter.format(Calendar.getInstance().getTime());  
                       Bundle data=new Bundle();
                       data.putString("time", time);
                       message.setData(data);                    
                        //得到客户端的信使对象,并向它发送消息
                        cMessenger = msg.replyTo;
                        cMessenger.send(message);
                    } catch (RemoteException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    break;
                default:
                    super.handleMessage(msg);
                }
    
            }
        };
        private Messenger mMessenger = new Messenger(mHandler);// 自己的信使对象
        private Messenger cMessenger;//客户的信使
    
        @Override
        public void onDestroy() {
            // TODO Auto-generated method stub
            Log.i(TAG, "onDestroy");
            cMessenger = null;
            super.onDestroy();
        }
        @Override
        public boolean onUnbind(Intent intent) {
            // TODO Auto-generated method stub
            Log.i(TAG, "onUnbind");
            return super.onUnbind(intent);
        }
        @Override
        public IBinder onBind(Intent intent) {
            // TODO Auto-generated method stub
            Log.i(TAG, "onBind");
            //返回自己信使的binder,以供客户端通过这个binder得到服务端的信使对象(通过new Messenger(binder))
            return mMessenger.getBinder();
        }
        @Override
        public void onRebind(Intent intent) {
            // TODO Auto-generated method stub
            Log.i(TAG, "onRebind");
    
        }
    
    }

    //布局文件

    <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
       >
    
        <TextView
            android:id="@+id/callback"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_alignParentTop="true"
            android:layout_marginTop="60dp"
            android:text="TextView" />
    
        <Button
            android:id="@+id/unbind"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@+id/callback"
            android:layout_centerHorizontal="true"
            android:layout_marginTop="152dp"
            android:text="解除绑定" />
    
        <Button
            android:id="@+id/bind"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignBaseline="@+id/unbind"
            android:layout_alignBottom="@+id/unbind"
            android:layout_toLeftOf="@+id/unbind"
            android:text="绑定" />
    
        <Button
            android:id="@+id/msg"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignBaseline="@+id/unbind"
            android:layout_alignBottom="@+id/unbind"
            android:layout_toRightOf="@+id/unbind"
            android:text="发送消息" />
       
        </RelativeLayout>
  • 相关阅读:
    2019年春季学期第三周作业
    第十二周作业
    十一周作业
    第十周作
    第九周作业
    第八周作业
    第七周作业
    第六周作业
    第五周作业
    第四周作业
  • 原文地址:https://www.cnblogs.com/sklww/p/3386373.html
Copyright © 2011-2022 走看看