[英]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.