当前位置:   article > 正文

Android Messenger的使用(配源码)

android messenger

零、完整源代码

链接: https://github.com/jx0260/TestGradle

一、写服务端

public class MessengerService extends Service {

    private String TAG = "MessengerService";

    private Handler mHandler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);

            Bundle data = msg.getData();
            if (data.getInt("code") == 1) {
                String objStr = data.getString("obj");
                Log.i(TAG, "Server: receive " + objStr + " - is blue!");

                Messenger clientMsger = msg.replyTo;
                if (clientMsger != null) {
                    Message receiptMsg = new Message();
                    Bundle bundle = new Bundle();
                    bundle.putString("cont", "I'm server, I received: sky is blue.");
                    receiptMsg.setData(bundle);

                    try {
                        Log.i(TAG, "Server send back received msg.");
                        clientMsger.send(receiptMsg);
                    } catch (RemoteException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    };

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return new Messenger(mHandler).getBinder();
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38

创建一个Service,MessengerService,声明 private Handler mHandler = new Handler 一个成员变量,此Handler用于处理来自客户端的请求。
在 onBind() 方法中,创建一个Messenger 对象(指定Handler)并返回给客户端。
配一下manifest.xml ( 注意 android:exported=“true”)

<service
    android:name=".MessengerService"
    android:enabled="true"
    android:exported="true">
    <intent-filter>
        <action android:name="com.example.testgradle.MessengerService"/>
    </intent-filter>
</service>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

二、写客户端

private Messenger mClientMessenger;

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
	Intent messengerIntent = new Intent("com.example.testgradle.MessengerService");
	messengerIntent.setPackage("com.example.testgradle");
	bindService(messengerIntent, new ServiceConnection() {
	    @Override
	    public void onServiceConnected(ComponentName name, IBinder service) {
	        mClientMessenger = new Messenger(service);
	        sendMessageToServer();
	    }
	
	    @Override
	    public void onServiceDisconnected(ComponentName name) {
	
	    }
	}, BIND_AUTO_CREATE);
	
	findViewById(R.id.btn_send_msg_to_server).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            sendMessageToServer();
        }
    });
}

private void sendMessageToServer() {
    Log.i(TAG, "send msg to server...(sky)");
    Message msg = Message.obtain();
    Bundle bundle = new Bundle();
    bundle.putString("obj", "sky");
    bundle.putInt("code", 1);
    msg.setData(bundle);

    Log.i(TAG, "pass the client's Messenger to Server!");
    msg.replyTo = new Messenger(mReceiveHandler);

    try {
        mClientMessenger.send(msg);
    } catch (RemoteException e) {
        e.printStackTrace();
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45

在 onServiceConnected () 回调中,将IBinder 对象,重新封装成 Messenger。
在 sendMessageToServer() 方法中,构造 Message 传入数据,通过 mClientMessenger 发送出去。
注:此处构造的 Message msg = Message.obtain(); 在封装数据时,必须使用 Bundle,跨进程通信底层用的是 Parcelable 接口,而Bundle的实现如下:

public final class Bundle implements Parcelable
  • 1

如果不使用Bundle,会报空Parcelable 的异常。

三、运行 客户端发到服务端进行处理

打印日志:

com.example.clientdemo I/ClientActivity: send msg to server...(sky)
com.example.clientdemo I/ClientActivity: pass the client's Messenger to Server!
com.example.testgradle I/MessengerService: Server: receive sky - is blue!
com.example.testgradle I/MessengerService: Server send back received msg.
com.example.clientdemo I/ClientActivity: Client received:I'm server, I received: sky is blue.
  • 1
  • 2
  • 3
  • 4
  • 5

四、服务端给客户端 回传数据

4.1客户端处理

Log.i(TAG, "pass the client's Messenger to Server!");
msg.replyTo = new Messenger(mReceiveHandler);
  • 1
  • 2

我们在构造往服务端发送的Message时,向其中设置了一个 replyTo,其值为 new 一个Messenger,指定了一个在客户端创建的 mReceiveHandler 用来处理从服务端传来的消息:

private Handler mReceiveHandler = new Handler(Looper.getMainLooper()) {
    @Override
    public void handleMessage(@NonNull Message msg) {
        super.handleMessage(msg);

        Bundle data = msg.getData();
        String cont = data.getString("cont");
        Log.i(TAG, "Client received:" + cont);
    }
};
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

简单说就是把一个客户端的 Messenger 传到了服务端,服务端使用此对象,向客户端回发数据。

4.2 服务端处理

Messenger clientMsger = msg.replyTo;
if (clientMsger != null) {
    Message receiptMsg = new Message();
    Bundle bundle = new Bundle();
    bundle.putString("cont", "I'm server, I received: sky is blue.");
    receiptMsg.setData(bundle);

    try {
        Log.i(TAG, "Server send back received msg.");
        clientMsger.send(receiptMsg);
    } catch (RemoteException e) {
        e.printStackTrace();
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14

注意,往客户端回发时,一样要使用Bundle。

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/菜鸟追梦旅行/article/detail/122598
推荐阅读
相关标签
  

闽ICP备14008679号