[关闭]
@cxm-2016 2016-08-12T17:08:46.000000Z 字数 1925 阅读 1444

使用Messenger进行进程通信

android no


1,创建服务端进程

  1. class MessengerService : Service() {
  2. private val TAG = "--${MessengerService::class.java.simpleName}--"
  3. private val messageHandler = Messenger(object : Handler() {
  4. override fun handleMessage(msg: Message) {
  5. when (msg.what) {
  6. Constants.FROM_CLIENT.value -> {
  7. //1,打印接受到的消息
  8. Log.e(TAG, "receive message from client:${msg.data.getString("msg")}")
  9. //2,回复消息
  10. var client = msg.replyTo
  11. var replyMessage = Message.obtain()
  12. replyMessage.what = Constants.FROM_SERVICE.value
  13. val data = Bundle()
  14. data.putString("reply", "Nice to meet you")
  15. replyMessage.data = data
  16. client.send(replyMessage)
  17. }
  18. else -> {
  19. }
  20. }
  21. }
  22. })
  23. override fun onBind(intent: Intent?): IBinder = messageHandler.binder
  24. }

2,创建客户端进程

  1. class MainActivity : AppCompatActivity() {
  2. private val TAG = "--${MainActivity::class.java.simpleName}--"
  3. //连接成功后获得,用于发送消息给服务端
  4. private var sender: Messenger? = null
  5. //将此对象传递给服务端可以接受并处理服务端发送的消息
  6. private val messageHandler = Messenger(object : Handler() {
  7. override fun handleMessage(msg: Message) {
  8. when (msg.what) {
  9. Constants.FROM_SERVICE.value -> {
  10. Log.e(TAG, "receive message from Service:${msg.data.getString("reply")}")
  11. }
  12. else -> {
  13. }
  14. }
  15. }
  16. })
  17. private val conn = object : ServiceConnection {
  18. override fun onServiceDisconnected(name: ComponentName?) {
  19. }
  20. override fun onServiceConnected(name: ComponentName?, service: IBinder?) {
  21. //一旦连接成功就向服务器发送消息
  22. this@MainActivity.sender = Messenger(service)
  23. val msg = Message.obtain()
  24. msg.what = Constants.FROM_CLIENT.value
  25. val data = Bundle()
  26. data.putString("msg", "hello! I'm client")
  27. msg.data = data
  28. //如果需要接受服务端的回复消息的话就必须将处理器传递给服务端
  29. msg.replyTo = messageHandler
  30. this@MainActivity.sender?.send(msg)
  31. }
  32. }
  33. override fun onCreate(savedInstanceState: Bundle?) {
  34. super.onCreate(savedInstanceState)
  35. setContentView(R.layout.activity_main)
  36. //准备建立连接
  37. val intent = Intent()
  38. intent.action = "myService"
  39. bindService(intent, conn, Context.BIND_AUTO_CREATE)
  40. }
  41. override fun onDestroy() {
  42. unbindService(conn)
  43. super.onDestroy()
  44. }
  45. }

注意:由于服务端是Service所以必须要在清单文件中注册

  1. <service
  2. android:name=".MessengerService"
  3. android:process=":remote">
  4. <intent-filter>
  5. <action android:name="myService" />
  6. </intent-filter>
  7. </service>
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注