@cxm-2016
2016-08-12T17:08:46.000000Z
字数 1925
阅读 1468
android
no
1,创建服务端进程
class MessengerService : Service() {
private val TAG = "--${MessengerService::class.java.simpleName}--"
private val messageHandler = Messenger(object : Handler() {
override fun handleMessage(msg: Message) {
when (msg.what) {
Constants.FROM_CLIENT.value -> {
//1,打印接受到的消息
Log.e(TAG, "receive message from client:${msg.data.getString("msg")}")
//2,回复消息
var client = msg.replyTo
var replyMessage = Message.obtain()
replyMessage.what = Constants.FROM_SERVICE.value
val data = Bundle()
data.putString("reply", "Nice to meet you")
replyMessage.data = data
client.send(replyMessage)
}
else -> {
}
}
}
})
override fun onBind(intent: Intent?): IBinder = messageHandler.binder
}
2,创建客户端进程
class MainActivity : AppCompatActivity() {
private val TAG = "--${MainActivity::class.java.simpleName}--"
//连接成功后获得,用于发送消息给服务端
private var sender: Messenger? = null
//将此对象传递给服务端可以接受并处理服务端发送的消息
private val messageHandler = Messenger(object : Handler() {
override fun handleMessage(msg: Message) {
when (msg.what) {
Constants.FROM_SERVICE.value -> {
Log.e(TAG, "receive message from Service:${msg.data.getString("reply")}")
}
else -> {
}
}
}
})
private val conn = object : ServiceConnection {
override fun onServiceDisconnected(name: ComponentName?) {
}
override fun onServiceConnected(name: ComponentName?, service: IBinder?) {
//一旦连接成功就向服务器发送消息
this@MainActivity.sender = Messenger(service)
val msg = Message.obtain()
msg.what = Constants.FROM_CLIENT.value
val data = Bundle()
data.putString("msg", "hello! I'm client")
msg.data = data
//如果需要接受服务端的回复消息的话就必须将处理器传递给服务端
msg.replyTo = messageHandler
this@MainActivity.sender?.send(msg)
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
//准备建立连接
val intent = Intent()
intent.action = "myService"
bindService(intent, conn, Context.BIND_AUTO_CREATE)
}
override fun onDestroy() {
unbindService(conn)
super.onDestroy()
}
}
注意:由于服务端是Service所以必须要在清单文件中注册
<service
android:name=".MessengerService"
android:process=":remote">
<intent-filter>
<action android:name="myService" />
</intent-filter>
</service>