简体   繁体   English

Android 捆绑使用

[英]Android Bundle usage

Is it possible to use Android Bundle to create and putString() in Activity then getString() in Service on button click?是否可以使用 Android Bundle在 Activity 中创建和 putString putString() ,然后在单击按钮时在服务中使用getString()

If not what can i do?如果不是我该怎么办?

Example例子

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

You can add static method in your service:您可以在服务中添加 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)
            }
        }
    }
}

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)然后从您的活动中调用它: 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