问题
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