如何通过 Messenger 在点击时发送远程服务消息

huangapple go评论70阅读模式
英文:

How to send remote service message onclick via Messenger

问题

以下是翻译好的部分:

我在Android和Kotlin方面还很新。我有一个服务器应用和一个客户端应用。我想从服务器向客户端应用发送字符串。我可以启动服务器,然后将其绑定到客户端应用,但是当我点击按钮时无法发送我的消息。

这是我的服务器部分:

private inner class MessageRequestHandler : Handler() {
    override fun handleMessage(msg: Message) {
        when (msg.what) {
            SEND_MESSAGE_FLAG -> {
                val bundle = Bundle()
                bundle.putString("key", "Test")

                val mesg = Message.obtain(null, SEND_MESSAGE_FLAG)
                mesg.obj = bundle
                try {
                    msg.replyTo.send(mesg)
                } catch (e: RemoteException) {
                    Log.i(TAG, "Error: " + e.message)
                }
            }
        }
        super.handleMessage(msg)
    }
}

private val messageMessenger: Messenger = Messenger(MessageRequestHandler())
override fun onBind(intent: Intent?): IBinder {
    return messageMessenger.binder
}

companion object {
    private val TAG = MyService::class.java.simpleName
    var SEND_MESSAGE_FLAG = 0
}

这是服务器的主要活动:

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)
    serviceIntent = Intent(applicationContext, MyService::class.java)
}

fun sendLogin(view: View){
    startService(serviceIntent)
    Toast.makeText(applicationContext, "Service Started", Toast.LENGTH_SHORT).show()
}

fun sendPay(view: View){
    Log.i(TAG, "Self Payment")
}

fun sendLogout(view: View){
    stopService(serviceIntent)
    Toast.makeText(applicationContext, "Service Stopped", Toast.LENGTH_SHORT).show()
}

这是客户端的主要活动:

private var serviceIntent: Intent? = null
var requestMessenger: Messenger? = null
var receiveMessenger: Messenger? = null
private var mIsBound = false
private var messageValue = 0

companion object {
    const val GET_RANDOM_NUMBER_FLAG = 0
}

internal inner class recieveHandler : Handler() {
    override fun handleMessage(msg: Message) {
        messageValue = 0
        when (msg.what) {
            GET_RANDOM_NUMBER_FLAG -> {
                messageValue = msg.arg1 
                Toast.makeText(applicationContext,"Server: $messageValue",Toast.LENGTH_LONG).show()
                println(messageValue) 
            }
            else -> {
            }
        }
        super.handleMessage(msg)
    }
}

var serviceConnection: ServiceConnection? = object : ServiceConnection {
    override fun onServiceDisconnected(arg0: ComponentName) {
        requestMessenger = null
        receiveMessenger = null
        mIsBound = false
    }

    override fun onServiceConnected(arg0: ComponentName, binder: IBinder) {
        requestMessenger = Messenger(binder)
        receiveMessenger = Messenger(recieveHandler())
        mIsBound = true
    }
}

fun bindServer(v: View) {
    serviceConnection?.let { bindService(serviceIntent, it, BIND_AUTO_CREATE) }
    if (mIsBound){
        Toast.makeText(applicationContext, "Service bound", Toast.LENGTH_SHORT).show()
    }
    else{
        Toast.makeText(applicationContext, "Service not bound", Toast.LENGTH_SHORT).show()
    }
}

fun getMessage(view: View) {
    if (mIsBound) {
        val requestMessage = Message.obtain(null, GET_RANDOM_NUMBER_FLAG)
        requestMessage.replyTo = receiveMessenger
        try {
            requestMessenger!!.send(requestMessage)
        } catch (e: RemoteException) {
            e.printStackTrace()
        }
    } else {
        Toast.makeText(
            applicationContext,
            "Service Unbound, can't get message",
            Toast.LENGTH_SHORT
        ).show()
    }
}

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

    serviceIntent = Intent()
    serviceIntent!!.component = ComponentName("com.my.server", "com.my.server.MyService")
}

你有什么建议吗?

英文:

I'm really new on Android and Kotlin.I have one Server app and one Client app. I want to send string from Server to Client app.I can start Server and then bind with Client app to Server but i cannot send my message when button click.
Here my Server :

 private inner class MessageRequestHandler : Handler() {
override fun handleMessage(msg: Message) {
when (msg.what) {
SEND_MESSAGE_FLAG -> {
val bundle = Bundle()
bundle.putString("key", "Test")
val mesg = Message.obtain(null, SEND_MESSAGE_FLAG)
mesg.obj = bundle
try {
msg.replyTo.send(mesg)
} catch (e: RemoteException) {
Log.i(TAG, "Error: " + e.message)
}                }
}
super.handleMessage(msg)
}
}
private val messageMessenger: Messenger = Messenger(MessageRequestHandler())
override fun onBind(intent: Intent?): IBinder {
return messageMessenger.binder
}
companion object {
private val TAG = MyService::class.java.simpleName
var SEND_MESSAGE_FLAG = 0
}

Here my Main activity of Server

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
serviceIntent = Intent(applicationContext, MyService::class.java)
}
fun sendLogin(view: View){
startService(serviceIntent)
Toast.makeText(applicationContext, "Service Started", Toast.LENGTH_SHORT).show()
}
fun sendPay(view: View){//When i press button i want to send message to Client from here
Log.i(TAG, "Self Payment")
}
fun sendLogout(view: View){
stopService(serviceIntent)
Toast.makeText(applicationContext, "Service Stopped", Toast.LENGTH_SHORT).show()
}

Here my Client Main Activity

private var serviceIntent: Intent? = null
var requestMessenger: Messenger? = null
var receiveMessenger: Messenger? = null
private var mIsBound = false
private var messageValue = 0
companion object {
const val GET_RANDOM_NUMBER_FLAG = 0
}
internal inner class recieveHandler : Handler() {
override fun handleMessage(msg: Message) {
messageValue = 0
when (msg.what) {
GET_RANDOM_NUMBER_FLAG -> {
messageValue = msg.arg1 
Toast.makeText(applicationContext,"Server: $messageValue",Toast.LENGTH_LONG).show()
println(messageValue) 
}
else -> {
}
}
super.handleMessage(msg)
}
}
var serviceConnection: ServiceConnection? = object : ServiceConnection {
override fun onServiceDisconnected(arg0: ComponentName) {
requestMessenger = null
receiveMessenger = null
mIsBound = false
}
override fun onServiceConnected(arg0: ComponentName, binder: IBinder) {
requestMessenger = Messenger(binder)
receiveMessenger = Messenger(recieveHandler())
mIsBound = true
}
}
fun bindServer(v: View) {
serviceConnection?.let { bindService(serviceIntent, it, BIND_AUTO_CREATE) }
if (mIsBound){
Toast.makeText(applicationContext, "Service bound", Toast.LENGTH_SHORT).show()
}
else{
Toast.makeText(applicationContext, "Service not bound", Toast.LENGTH_SHORT).show()
}
}
fun getMessage(view: View) {
if (mIsBound) {
val requestMessage = Message.obtain(null, GET_RANDOM_NUMBER_FLAG)
requestMessage.replyTo = receiveMessenger
try {
requestMessenger!!.send(requestMessage)
} catch (e: RemoteException) {
e.printStackTrace()
}
} else {
Toast.makeText(
applicationContext,
"Service Unbound, can't get message",
Toast.LENGTH_SHORT
).show()
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
serviceIntent = Intent()
serviceIntent!!.component = ComponentName("com.my.server", "com.my.server.MyService")
}

What you can suggest me?

答案1

得分: 1

经过5天的挑战,我基本上找到了解决方法。

  1. 我正在使用EventBus从Activity发送消息到Service,在这里有一个示例
  2. 在Service中使用局部变量接收已发送的消息。
  3. 发送到另一个应用。
英文:

After 5 days challenging , i found way basically how to do.

  1. I'm sending message from Activity to Service with EventBus here is example
  2. Getting sent message with local variable in Service
  3. Sending to another app

huangapple
  • 本文由 发表于 2020年10月22日 16:43:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/64478498.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定