安卓使用Messenger进行进程间通信

Messenger的主要作用是进程间消息的传递。

第一步,MyConstants常量,用以标识客户端和服务端,可选。

public class MyConstants {
    public static final int MSG_FROM_CLIENT = 1001;
    public static final int MSG_FROM_SERVICE = 1002;

}

第二步,先创建服务端

public class MessengerService extends Service {

    private static final String TAG = "MessengerService";

//    1、创建handler
    private static class MessengerHandler extends Handler {
//        处理消息
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);

            switch (msg.what) {
                case MyConstants.MSG_FROM_CLIENT:
                    Log.d(TAG, "handleMessage: receive message from client : "+msg.getData().getString("msg"));
//                    将消息回复给客户端
                    Messenger client = msg.replyTo;
                    Message replyMessage = Message.obtain(null, MyConstants.MSG_FROM_SERVICE);
                    Bundle bundle = new Bundle();
                    bundle.putString("reply","ok,消息已收到,稍后回复。");
                    replyMessage.setData(bundle);
                    try {
                        client.send(replyMessage);
                    } catch (RemoteException e) {
                        e.printStackTrace();
                    }
                    break;
                default:
                    super.handleMessage(msg);
            }
        }
    }

//    2、使用Handler去创建一个Messenger
    private final Messenger mMessenger = new Messenger(new MessengerHandler());

//    3、返回Messenger中的Binder对象
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return mMessenger.getBinder();
    }
}

第三步,创建客户端

public class IpcActivity extends AppCompatActivity {

    private static final String TAG = "IpcActivity";

//    1、创建参数,ServiceConnection对象用以和服务端建立连接
    private Messenger mService;
    private ServiceConnection mConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
//            将消息发送至服务端
            mService = new Messenger(service);
            Message msg = Message.obtain(null,MyConstants.MSG_FROM_CLIENT);
            Bundle data = new Bundle();
            data.putString("msg","hello,this is client.");
            msg.setData(data);

            msg.replyTo = mMessenger;

            try {
                mService.send(msg);
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {

        }
    };

//  2、创建Handler
    private static class MessengerHandler extends Handler {
//        处理来自服务端的消息
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case MyConstants.MSG_FROM_SERVICE:
                    Log.d(TAG, "handleMessage: receive message from Service : "+msg.getData().getString("reply"));
                default:
                    super.handleMessage(msg);
            }
        }
    }
// 3、创建Messenger
    private final Messenger mMessenger = new Messenger(new MessengerHandler());

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
//        4、绑定并创建服务
        Intent intent = new Intent(this, MessengerService.class);
        bindService(intent,mConnection, Context.BIND_AUTO_CREATE);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
//        5、解绑服务
        unbindService(mConnection);
    }

}

第四步,在AndroidManifest文件中添加Service标签,并让Service单独在一个进程上运行

<service
            android:name=".ipc.MessengerService"
            android:process=":server">
</service>

 

由于Messenger是以串行的方式去处理客户端发送过来的消息的,如果服务端要处理大量的并发请求,使用Messenger就有点不合适了,而且也不能跨进程调用服务端的方法。

发布了2 篇原创文章 · 获赞 2 · 访问量 1178
展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 大白 设计师: CSDN官方博客

分享到微信朋友圈

×

扫一扫,手机浏览