当前位置:   article > 正文

【Android】使用Messenger实现进程间通讯_android messenger跨进程parcelable

android messenger跨进程parcelable

1 Messenger 简介

        Messenger 类实现了 Parcelable 接口,用于进程间传输并处理消息,调用流程如下:

  • Client 通过 bindService() 请求绑定 Service
  • Service 通过 messenger_s.getBinder() 获取 IBunder 并返回 Client
  • Client 通过 messenger_s =new Messenger(service) 获取 Service 的 Messenger
  • Client 通过 msg_c2s.replyTo=messenger_c 将自己的 Messenger 绑定到 msg_c2s
  • Client 通过 messenger_s.send(msg_c2s) 给 Service 发送消息
  • Service 通过 messenger_c=msg_c2s.replyTo 获取 Client 的 Messenger
  • Service 通过 messenger_c.send(msg_s2c) 给 Client 发送消息

        本文全部代码见→使用Messenger实现进程间通讯

2 项目结构

3 服务端 msger_S 代码

        (1)创建服务

        MyService.java

  1. package com.example.msger_s;
  2. import android.app.Service;
  3. import android.content.Intent;
  4. import android.os.Bundle;
  5. import android.os.Handler;
  6. import android.os.IBinder;
  7. import android.os.Message;
  8. import android.os.Messenger;
  9. import android.os.RemoteException;
  10. import android.util.Log;
  11. public class MyService extends Service {
  12. Messenger messenger_c; //客户端的Messenger
  13. @Override
  14. public IBinder onBind(Intent intent) {
  15. return messenger_s.getBinder();
  16. }
  17. private Messenger messenger_s = new Messenger(new Handler() {
  18. @Override
  19. public void handleMessage(Message msg_c2s) {
  20. super.handleMessage(msg_c2s);
  21. receive(msg_c2s);
  22. messenger_c = msg_c2s.replyTo; //获取客户端的Messenger
  23. send();
  24. }
  25. });
  26. private void receive(Message msg) { //接收来自客户端的消息
  27. Bundle bundle = (Bundle) msg.obj;
  28. String msg_c2s = bundle.getString("msg_c2s");
  29. Log.e("MyService", "来自客户端的消息:" + msg_c2s);
  30. }
  31. private void send() { //给客户端返回消息
  32. Message msg = new Message();
  33. Bundle bundle1 = new Bundle();
  34. bundle1.putString("msg_s2c", "hello client");
  35. msg.obj = bundle1;
  36. try {
  37. messenger_c.send(msg);
  38. } catch (RemoteException e) {
  39. e.printStackTrace();
  40. }
  41. }
  42. }

        (2)注册服务

        在 AndroidManifest.xml 文件中 application 节点下注册 service,如下。

  1. <service
  2. android:name=".MyService"
  3. android:exported="true">
  4. <intent-filter>
  5. <action android:name="com.xxx.msger_s"/>
  6. <category android:name="android.intent.category.DEFAULT" />
  7. </intent-filter>
  8. </service>

        (3)主 Activity

        MainActivity.java

  1. package com.example.msger_s;
  2. import android.support.v7.app.AppCompatActivity;
  3. import android.os.Bundle;
  4. public class MainActivity extends AppCompatActivity {
  5. @Override
  6. protected void onCreate(Bundle savedInstanceState) {
  7. super.onCreate(savedInstanceState);
  8. setContentView(R.layout.activity_main);
  9. }
  10. }

4 客户端 msger_C 代码

        (1)设计布局

        activity_main.xml

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  3. xmlns:tools="http://schemas.android.com/tools"
  4. android:layout_width="match_parent"
  5. android:layout_height="match_parent"
  6. android:paddingBottom="@dimen/activity_vertical_margin"
  7. android:paddingLeft="@dimen/activity_horizontal_margin"
  8. android:paddingRight="@dimen/activity_horizontal_margin"
  9. android:paddingTop="@dimen/activity_vertical_margin"
  10. android:orientation="vertical"
  11. tools:context="com.example.msger_c.MainActivity">
  12. <EditText
  13. android:id="@+id/et_send"
  14. android:layout_width="match_parent"
  15. android:layout_height="80dp"
  16. android:text="hello service"
  17. android:textSize="30dp"
  18. android:background="#ffcc66"/>
  19. <Button
  20. android:id="@+id/btn_send"
  21. android:layout_width="match_parent"
  22. android:layout_height="wrap_content"
  23. android:layout_gravity="center_horizontal"
  24. android:layout_marginTop="30dp"
  25. android:textSize="30sp"
  26. android:text="发送"/>
  27. <TextView
  28. android:layout_width="match_parent"
  29. android:layout_height="wrap_content"
  30. android:text="返回的消息:"
  31. android:textSize="30sp"
  32. android:layout_marginTop="100dp"/>
  33. <TextView
  34. android:id="@+id/tv_receive"
  35. android:layout_width="match_parent"
  36. android:layout_height="80dp"
  37. android:textSize="30sp"
  38. android:background="#ffcc66"
  39. android:layout_marginTop="20dp"/>
  40. </LinearLayout>

        界面如下:

        (2)主 Activity

        MainActivity.java

  1. package com.example.msger_c;
  2. import android.app.Activity;
  3. import android.content.ComponentName;
  4. import android.content.Context;
  5. import android.content.Intent;
  6. import android.content.ServiceConnection;
  7. import android.os.Bundle;
  8. import android.os.Handler;
  9. import android.os.IBinder;
  10. import android.os.Message;
  11. import android.os.Messenger;
  12. import android.os.RemoteException;
  13. import android.support.v7.app.AppCompatActivity;
  14. import android.view.View;
  15. import android.view.inputmethod.InputMethodManager;
  16. import android.widget.Button;
  17. import android.widget.EditText;
  18. import android.widget.TextView;
  19. public class MainActivity extends AppCompatActivity {
  20. private Messenger messenger_s; //服务端的Messenger
  21. private EditText et_send;
  22. private Button btn_send;
  23. private TextView tv_receive;
  24. @Override
  25. protected void onCreate(Bundle savedInstanceState) {
  26. super.onCreate(savedInstanceState);
  27. setContentView(R.layout.activity_main);
  28. init();
  29. }
  30. private void init() {
  31. et_send = (EditText) findViewById(R.id.et_send);
  32. btn_send = (Button) findViewById(R.id.btn_send);
  33. tv_receive = (TextView) findViewById(R.id.tv_receive);
  34. btn_send.setOnClickListener(cl);
  35. }
  36. View.OnClickListener cl = new View.OnClickListener(){
  37. @Override
  38. public void onClick(View v) {
  39. hideInputMethod(MainActivity.this, v); //关闭输入法
  40. if (v.getId()==R.id.btn_send) {
  41. String msg_c2s = et_send.getText().toString();
  42. sendMsg(msg_c2s);
  43. }
  44. }
  45. };
  46. private void sendMsg(String msg_c2s){
  47. if (messenger_s==null) {
  48. attemptToBindService();
  49. }
  50. Message msg = new Message();
  51. Bundle bundle = new Bundle();
  52. bundle.putString("msg_c2s",msg_c2s);
  53. msg.obj = bundle;
  54. msg.replyTo = messenger_c; //将客户端的Messenger传给服务端
  55. try {
  56. messenger_s.send(msg);
  57. } catch (RemoteException e) {
  58. e.printStackTrace();
  59. }
  60. }
  61. private Messenger messenger_c = new Messenger(new Handler() { //客户端的Messenger
  62. @Override
  63. public void handleMessage(Message msg) { //处理服务端返回的消息
  64. super.handleMessage(msg);
  65. Bundle bundle = (Bundle) msg.obj;
  66. String msg_s2c = bundle.getString("msg_s2c");
  67. tv_receive.setText(msg_s2c);
  68. }
  69. });
  70. private void attemptToBindService() {
  71. Intent intent = new Intent();
  72. intent.setAction("com.xxx.msger_s");
  73. intent.setPackage("com.example.msger_s");
  74. bindService(intent, conn, Context.BIND_AUTO_CREATE);
  75. }
  76. ServiceConnection conn = new ServiceConnection() {
  77. @Override
  78. public void onServiceConnected(ComponentName name, IBinder service) {
  79. messenger_s = new Messenger(service); //获取服务端的Messenger
  80. }
  81. @Override
  82. public void onServiceDisconnected(ComponentName name) {
  83. messenger_s = null;
  84. }
  85. };
  86. private void hideInputMethod(Activity act, View v) { //关闭输入法
  87. InputMethodManager imm = (InputMethodManager) act.getSystemService(Context.INPUT_METHOD_SERVICE);
  88. imm.hideSoftInputFromWindow(v.getWindowToken(),0);
  89. }
  90. @Override
  91. protected void onStart() {
  92. super.onStart();
  93. if (messenger_s==null) {
  94. attemptToBindService();
  95. }
  96. }
  97. @Override
  98. protected void onStop() {
  99. super.onStop();
  100. if (messenger_s!=null) {
  101. unbindService(conn);
  102. }
  103. }
  104. }

5 效果展示

        点击【发送】按钮,在服务端可以收到发送的消息,如下:

        在客户端收到回复如下:

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

闽ICP备14008679号