How to send string data from Activity to started Service onclick method?

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

How to send string data from Activity to started Service onclick method?

问题

以下是您要翻译的内容:

我有一个活动和一个服务。应用程序上有三个按钮。其中一个是“开始”按钮,用于启动服务;另一个是“测试”按钮,用于发送“Test”字符串到服务;最后一个是“停止”按钮,用于停止服务。

我可以正常启动和停止服务,但是当我尝试发送字符串时,我尝试了Intent,但是找不到任何方法来实现这一点。我还尝试了onStartCommand(),但是这个方法也无法触发。

您有什么建议吗?

这是我的活动部分:

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)
    if (isMyServiceRunning(MyService::class.java)){
        Toast.makeText(applicationContext, "Service Started", Toast.LENGTH_SHORT).show()
    }
}

fun sendTest(view: View){ //尝试发送“TEST”
    val intent = Intent(this, MyService::class.java)
    val msj = "TEST"
    intent.putExtra("key", msj)
    applicationContext.startService(intent)
}

fun sendLogout(view: View){ //停止服务
    stopService(serviceIntent)
    if (!isMyServiceRunning(MyService::class.java)){
        Toast.makeText(applicationContext, "Service Stopped", Toast.LENGTH_SHORT).show()
    }
}

private fun isMyServiceRunning(serviceClass: Class<*>): Boolean { //检查应用程序是否已启动
    val manager = getSystemService(ACTIVITY_SERVICE) as ActivityManager
    for (service in manager.getRunningServices(Int.MAX_VALUE)) {
        if (serviceClass.name == service.service.className) {
            return true
        }
    }
    return false
}

这是我的服务部分:

private inner class MessageRequestHandler() : Handler()   {
    override fun handleMessage(msg: Message) {
        when (msg.what) {
            SEND_MESSAGE_FLAG -> {
                val bundle = Bundle()
                bundle.putString("key", stringMessage)
                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)
    }
}

override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int { //无法触发此方法...
    stringMessage = intent?.extras?.getString("key").toString()
    return super.onStartCommand(intent, flags, startId)
}

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

谢谢。

英文:

I have one activity and service. I have three button on app. One of is Start to start Service the other is Test to send Service "Test" string the other is Stop to stop service.

I can start and stop service without any problem but when i try to send string i tried Intent but cannot find any way for this. I also tried onStartCommand() but cannot fire that method too..

What you can suggest?

Here my Activity

 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)
    if (isMyServiceRunning(MyService::class.java)){
        Toast.makeText(applicationContext, &quot;Service Started&quot;, Toast.LENGTH_SHORT).show()
    }

}

fun sendTest(view: View){ //TRY TO SEND &quot;TEST&quot; 
    val intent = Intent(this, MyService::class.java)
    val msj = &quot;TEST&quot;
    intent.putExtra(&quot;key&quot;, msj)
    applicationContext.startService(intent);
}

fun sendLogout(view: View){ //Stop service
    stopService(serviceIntent)
    if (!isMyServiceRunning(MyService::class.java)){
        Toast.makeText(applicationContext, &quot;Service Stopped&quot;, Toast.LENGTH_SHORT).show()
    }

}

private fun isMyServiceRunning(serviceClass: Class&lt;*&gt;): Boolean { //Checking app is started or not
    val manager = getSystemService(ACTIVITY_SERVICE) as ActivityManager
    for (service in manager.getRunningServices(Int.MAX_VALUE)) {
        if (serviceClass.name == service.service.className) {
            return true
        }
    }
    return false
}

Here my service

private inner class MessageRequestHandler() : Handler()   {
    override fun handleMessage(msg: Message) {
        when (msg.what) {
            SEND_MESSAGE_FLAG -&gt; {
                val bundle = Bundle()
                bundle.putString(&quot;key&quot;, stringMessage)
                val mesg = Message.obtain(null, SEND_MESSAGE_FLAG)
                mesg.obj = bundle
                try {
                    msg.replyTo.send(mesg)
                } catch (e: RemoteException) {
                    Log.i(TAG, &quot;Error: &quot; + e.message)
                }
            }
        }

        super.handleMessage(msg)
    }

}

override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int { //Cannot fire this...
    stringMessage = intent?.extras?.getString(&quot;key&quot;).toString()
    return super.onStartCommand(intent, flags, startId)
}

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

Thanks

答案1

得分: 1

请检查,使用EventBus进行消息传递非常简单。以下是您的解决方案:

//定义事件类
class MessageEvent(val someString: String)

//主活动
class MainActivity : AppCompatActivity() {

    private lateinit var serviceIntent: Intent

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

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

    fun sendTest(view: View) {
        //发布事件
        EventBus.getDefault().post(MessageEvent("TEST"))
    }

    fun sendLogout(view: View) {
        stopService(serviceIntent)
        if (!isMyServiceRunning(MessageService::class.java)) {
            Toast.makeText(applicationContext, "Service Stopped", Toast.LENGTH_SHORT).show()
        }
    }

    private fun isMyServiceRunning(serviceClass: Class<*>): Boolean {
        val manager = getSystemService(ACTIVITY_SERVICE) as ActivityManager
        for (service in manager.getRunningServices(Int.MAX_VALUE)) {
            if (serviceClass.name == service.service.className) {
                return true
            }
        }
        return false
    }
}

//服务类
class MessageService : Service() {

    private val TAG: String? = "InService"

    private inner class MessageRequestHandler() : Handler() {
        override fun handleMessage(msg: Message) {
            super.handleMessage(msg)
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onMessageEvent(event: MessageEvent?) {
        Log.i(TAG, "onMessageEvent: " + event?.someString)
    }

    override fun onStart(intent: Intent?, startId: Int) {
        super.onStart(intent, startId)

        //订阅EventBus
        EventBus.getDefault().register(this);
    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        return super.onStartCommand(intent, flags, startId)
    }

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

    override fun onDestroy() {
        super.onDestroy()

        //取消订阅EventBus
        EventBus.getDefault().unregister(this);
    }
}
英文:

Please check, message passing is easy using EventBus. Here's your solution:

//Define Event Class
class MessageEvent(val someString: String)

Main Activity

class MainActivity : AppCompatActivity() {
private lateinit var serviceIntent: Intent
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
serviceIntent = Intent(applicationContext, MessageService::class.java)
}
fun sendLogin(view: View){
startService(serviceIntent)
if (isMyServiceRunning(MessageService::class.java)){
Toast.makeText(applicationContext, &quot;Service Started&quot;, Toast.LENGTH_SHORT).show()
}
}
fun sendTest(view: View){
//Post Events
EventBus.getDefault().post(MessageEvent(&quot;TEST&quot;))
}
fun sendLogout(view: View){
stopService(serviceIntent)
if (!isMyServiceRunning(MessageService::class.java)){
Toast.makeText(applicationContext, &quot;Service Stopped&quot;, Toast.LENGTH_SHORT).show()
}
}
private fun isMyServiceRunning(serviceClass: Class&lt;*&gt;): Boolean {
val manager = getSystemService(ACTIVITY_SERVICE) as ActivityManager
for (service in manager.getRunningServices(Int.MAX_VALUE)) {
if (serviceClass.name == service.service.className) {
return true
}
}
return false
}
}

And Service class

class MessageService : Service() {
private val TAG: String? = &quot;InService&quot;
private inner class MessageRequestHandler() : Handler()   {
override fun handleMessage(msg: Message) {
super.handleMessage(msg)
}
}
@Subscribe(threadMode = ThreadMode.MAIN)
fun onMessageEvent(event: MessageEvent?) {
Log.i(TAG, &quot;onMessageEvent: &quot; + event?.someString)
}
override fun onStart(intent: Intent?, startId: Int) {
super.onStart(intent, startId)
//subscribe to EventBus
EventBus.getDefault().register(this);
}
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
return super.onStartCommand(intent, flags, startId)
}
private val messageMessenger: Messenger = Messenger(MessageRequestHandler())
override fun onBind(intent: Intent?): IBinder {
return messageMessenger.binder
}
override fun onDestroy() {
super.onDestroy()
//Unsubscribe to EventBus
EventBus.getDefault().unregister(this);
}
}

huangapple
  • 本文由 发表于 2020年10月26日 03:59:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/64528168.html
匿名

发表评论

匿名网友

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

确定