Android Bundle usage

匆匆过客 提交于 2021-02-11 14:57:31

问题


Is it possible to use Android Bundle to create and putString() in Activity then getString() in Service on button click?

If not what can i do?

Example

MainActivity.kt

        val bundle = Bundle()
        bundle.putString("MyString", "Message")

        val mesg = Message.obtain(null, MyService.SEND_MESSAGE_FLAG)
        mesg.obj = bundle
        try {
            myService!!.send(mesg)
        } catch (e: RemoteException) {
        }

Service

override fun handleMessage(msg: Message) {
        when (msg.what) {
            SEND_MESSAGE_FLAG -> {
                val data = msg.data
                val dataString = data.getString("MyString")
                println(dataString)
                val mesg = Message.obtain(null, SEND_MESSAGE_FLAG)
                mesg.obj = dataString

                try {
                    msg.replyTo.send(mesg)
                } catch (e: RemoteException) {
                    Log.i(TAG, "Error: " + e.message)
                }
            }
        }

        super.handleMessage(msg)
    }

回答1:


You can add static method in your service:

companion object {
    private const val EXTRA_KEY_MY_STR = "EXTRA_KEY_MY_STR"

    fun startMyService(context: Context?, myStr: String?) {
        if (context != null) {
            val intent = Intent(context, MyService::class.java)
            intent.putExtra(EXTRA_KEY_MY_STR, myStr)
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                context.startForegroundService(intent)
            } else {
                context.startService(intent)
            }
        }
    }
}

then call it from your activity: MyService.startMyService(this, "MyString") and then get string in your onHandleIntent(): val myStr = intent?.extras?.getString(EXTRA_KEY_MY_STR)



来源:https://stackoverflow.com/questions/64522613/android-bundle-usage

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!