Detailed explanation of two-way communication between Android Messenger processes

Detailed explanation of two-way communication between Android Messenger processes

Before implementing Messenger communication, we must first complete a prerequisite: bind a component to the service by calling bindService (). This is what we have to do to bind the component to the service:
http://blog.csdn.net/q296264785/article/details/53418534 To
bind the client to the service, you must:

1、实现ServiceConnection。
        你的实现代码必须重写两个回调方法:
        onServiceConnected()
        系统调用该方法来传递服务的onBind()方法所返回的IBinder。
        onServiceDisconnected()
        当与服务的联接发生意外中断时,比如服务崩溃或者被杀死时,Android系统将会调用该方法。客户端解除绑定时,不会调用该方法。

private ServiceConnection conn = new ServiceConnection() {
        @Override
        public void onServiceDisconnected(ComponentName name) {
            // TODO Auto-generated method stub
        }
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            // TODO Auto-generated method stub
        }
    };
2、调用bindService(),传入已实现的ServiceConnection。
    @Override
    protected void onStart() {
        // TODO Auto-generated method stub
        super.onStart();
        Intent intent = new Intent(this, MService.class);
        bindService(intent, conn, IBinder.LAST_CALL_TRANSACTION);
    }
3、当系统调用你的onServiceConnected()回调方法时,你可以利用接口中定义的方法开始对服务的调用。
4、要断开与服务的联接,请调用unbindService()。

—————————————- I am the dividing line, the following starts data communication —————————-


Through the above steps, we have completed the determination of Service, and then we can achieve data communication. For easy understanding, we first implement one-way communication: Activity sends data to Service, here is the official API to communicate Things to do:

1、服务实现一个Handler ,用于客户端每次调用时接收回调。
2、此Handler用于创建一个Messenger对象(它是一个对Handler的引用)。
3、此Messenger对象创建一个IBinder,服务在onBind()中把它返回给客户端。
4、客户端用IBinder将Messenger(引用服务的Handler)实例化,客户端用它向服务发送消息对象Message。
5、服务接收Handler中的每个消息Message——确切的说,是在handleMessage()方法中接收。

Let's write the implementation class of Service first. After reading the above five points, the services that need to be implemented are: 1, 2, 3, and 5.

//1、服务实现一个Handler ,用于客户端每次调用时接收回调。
class MHandler extends Handler {}
//2、此Handler用于创建一个Messenger对象(它是一个对Handler的引用)。
Messenger messenger = new Messenger(new MHandler());
//3、此Messenger对象创建一个IBinder,服务在onBind()中把它返回给客户端。
@Override
    public IBinder onBind(Intent intent) {
        // TODO Auto-generated method stub
        return messenger.getBinder();
    }
//5、服务接收Handler中的每个消息Message——确切的说,是在handleMessage()方法中接收。
class MHandler extends Handler {
        @Override
        public void handleMessage(Message msg) {
            // TODO Auto-generated method stub
            super.handleMessage(msg);
            if (msg.what == 1) {
                System.out.println("--从Activity接受到的数据->>"
                        + msg.getData().getString("NUM"));
                //Toast打印数据
                Toast.makeText(getApplicationContext(), "接收到数据", 1).show();
            }
        }
    }

At this point, all the things we need to do in Service are done. Next is what the Activity needs to do:

//4、客户端用IBinder将Messenger(引用服务的Handler)实例化
private ServiceConnection conn = new ServiceConnection() {
        @Override
        public void onServiceDisconnected(ComponentName name) {
        }
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            messenger = new Messenger(service);
        }
    };
//客户端用它(messenger )向服务发送消息对象Message。
    Message message = Message.obtain(null, 1); //获得消息载体
    Bundle data = new Bundle();
    data.putString("NUM", "Activity信使");
    message.setData(data);//写入数据
    try {
        messenger.send(message);//发送数据
    } catch (RemoteException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

Here we have completed the one-way communication of Activity to Service, the principle of two-way communication and one-way communication is basically the same.
Start with the sending end (Service), in Service we need to add a piece of code to send data:

// 1、通过msg.replyTo获得Activity中message.replyTo = replyMessenger赋值的Messenger。
                Messenger messenger1 = msg.replyTo;
                Message message = Message.obtain(null, 2); // 2、获得一个Message,写入需要传递的数据。
                Bundle data = new Bundle();
                data.putString("NUM", "Service信使");
                message.setData(data);
                try {
                    messenger1.send(message);// 3、发送数据
                } catch (RemoteException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

We need to write another piece of data receiving code in Activity, the code is basically the same as the receiving code in Service just now, the receiving activity:

private Messenger replyMessenger = new Messenger(new Handler() {// 1、创建一个Handler实现并且通过这个实现创建一个Messenger的实现
                public void handleMessage(Message msg) {
                    switch (msg.what) {
                    case 2:
                        // 获取信息内容并Toast
                        Toast.makeText(MainActivity.this,
                                msg.getData().getString("NUM"), 0).show();// 3、获取Service传递过来的值
                        break;
                    default:
                        break;
                    }
                };
            });
message.replyTo = replyMessenger;// 2、将1获得的实现传递给replyTo

All source code:

The layout file only needs a Button

   <Button
        android:id="@+id/MSG_button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/button2"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="40dp"
        android:text="向Service发送数据" />

MainActivity:

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.view.View;
import android.view.View.OnClickListener;
import android.widget.Toast;

public class MainActivity extends Activity {
    private Messenger messenger;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        findViewById(R.id.MSG_button1).setOnClickListener(
                new OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        // TODO Auto-generated method stub
                        Message message = Message.obtain(null, 1);
                        Bundle data = new Bundle();
                        data.putString("NUM", "Activity信使");
                        message.setData(data);
                        // -------------
                        message.replyTo = replyMessenger;// 2、将1获得的实现传递给replyTo
                        try {
                            messenger.send(message);
                        } catch (RemoteException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    }
                });
    }

    private Messenger replyMessenger = new Messenger(new Handler() {// 1、创建一个Handler实现并且通过这个实现创建一个Messenger的实现
                public void handleMessage(Message msg) {
                    switch (msg.what) {
                    case 2:
                        // 获取信息内容并Toast
                        Toast.makeText(MainActivity.this,
                                msg.getData().getString("NUM"), 0).show();// 3、获取Service传递过来的值
                        break;
                    default:
                        break;
                    }
                };
            });

    @Override
    protected void onStart() {
        // TODO Auto-generated method stub
        super.onStart();
        Intent intent = new Intent(this, MService.class);
        bindService(intent, conn, IBinder.LAST_CALL_TRANSACTION);
    }

    private ServiceConnection conn = new ServiceConnection() {

        @Override
        public void onServiceDisconnected(ComponentName name) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            // TODO Auto-generated method stub
            messenger = new Messenger(service);
        }
    };
}

MService:

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

public class MService extends Service {
    class MHandler extends Handler {
        @Override
        public void handleMessage(Message msg) {
            // TODO Auto-generated method stub
            super.handleMessage(msg);
            if (msg.what == 1) {
                System.out.println("--从Activity接受到的数据->>"
                        + msg.getData().getString("NUM"));
                Toast.makeText(getApplicationContext(), "接收到数据", 1).show();
                // ----------------------------------------------
                // 1、通过msg.replyTo获得Activity中message.replyTo = replyMessenger赋值的Messenger。
                Messenger messenger1 = msg.replyTo;
                Message message = Message.obtain(null, 2); // 2、获得一个Message,写入需要传递的数据。
                Bundle data = new Bundle();
                data.putString("NUM", "Service信使");
                message.setData(data);
                try {
                    messenger1.send(message);// 3、发送数据
                } catch (RemoteException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
    }

    Messenger messenger = new Messenger(new MHandler());

    @Override
    public IBinder onBind(Intent intent) {
        // TODO Auto-generated method stub
        return messenger.getBinder();
    }

}

http://blog.csdn.net/q296264785/article/details/53418534

Published 34 original articles · Like 10 · Visits 30,000+

Guess you like

Origin blog.csdn.net/q296264785/article/details/53445206