繁体   English   中英

Android 捆绑使用

[英]Android Bundle usage

是否可以使用 Android Bundle在 Activity 中创建和 putString putString() ,然后在单击按钮时在服务中使用getString()

如果不是我该怎么办?

例子

主活动.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) {
        }

服务

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)
    }

您可以在服务中添加 static 方法:

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)
            }
        }
    }
}

然后从您的活动中调用它: MyService.startMyService(this, "MyString")然后在您的 onHandleIntent() 中获取字符串: val myStr = intent?.extras?.getString(EXTRA_KEY_MY_STR)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM