Android跨进程通信之Messenger

  • [Messenger简介]
  • [代码]
    1. [实现service端]
    2. [实现client端]
  • [效果]

Messenger简介

Messenger翻译为信使,是Android提供轻量级IPC(Inter-Process Communication,进程间通信)方案,底层实现为AIDL。
Messenger实现Parcelable接口,有两个构造方法,分别可传入IBinder对象或Handler对象

/**
   * Create a Messenger from a raw IBinder, which had previously been
   * retrieved with {@link #getBinder}.
   * 
   * @param target The IBinder this Messenger should communicate with.
   */
  public Messenger(IBinder target) {
      mTarget = IMessenger.Stub.asInterface(target);
  }
/**
  * Create a new Messenger pointing to the given Handler.  Any Message
  * objects sent through this Messenger will appear in the Handler as if
  * {@link Handler#sendMessage(Message) Handler.sendMessage(Message)} had
  * been called directly.
  * 
  * @param target The Handler that will receive sent messages.
  */
 public Messenger(Handler target) {
     mTarget = target.getIMessenger();
 }

代码

实现service端

首页创建一个服务类,继承Service

class MyService : Service() {

    override fun onCreate() {
        super.onCreate()
    }

    private val serviceHandler = Handler(Handler.Callback { msg ->
        Log.i("MessengerTest", "MyService->收到客户端消息")
        var clientMessenger = msg.replyTo
        clientMessenger.send(Message.obtain())
        true
    })

    private val serviceMessenger = Messenger(serviceHandler)

    override fun onBind(intent: Intent?): IBinder {
        return serviceMessenger.binder
    }
}

在清单文件中声明,注意process标签,作用在另一个进程中运行此服务


实现client端

class MainActivity : AppCompatActivity() {

    val clientHandler = Handler(Handler.Callback { msg ->
        Log.i("MessengerTest", "MainActivity->收到服务端消息")
        true
    })

    var clientServiceConnect = object : ServiceConnection {
        override fun onServiceConnected(name: ComponentName?, service: IBinder?) {
            val messenger = Messenger(service)
            var message = Message.obtain()
            message.replyTo = Messenger(clientHandler)
            messenger.send(message)
        }

        override fun onServiceDisconnected(name: ComponentName?) {
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        bind_btn.setOnClickListener { v ->
            run {
                var intent = Intent(this, MyService::class.java)
                bindService(intent, clientServiceConnect, BIND_AUTO_CREATE)
            }
        }
    }
}

效果

run后点击绑定服务按钮,log打印


log

你可能感兴趣的:(Android跨进程通信之Messenger)