How do I get data within an Android Service that was passed from an invoking Activity?
相关问题
- How can I create this custom Bottom Navigation on
- Bottom Navigation View gets Shrink Down
- How to make that the snackbar action button be sho
- Listening to outgoing sms not working android
- How to create Circular view on android wear?
Service: startservice can cause side affects,best way to use messenger and pass data.
Activity:Get Messenger from Intent fill it pass data and pass the message back to service
If you bind your service, you will get the Extra in
onBind(Intent intent)
.Activity:
Service:
Another posibility is using intent.getAction:
In Service:
In Activity:
Finally, In Manifest file:
Activity:
Service:
For a precise answer to this question on "How to send data via intent from an Activity to Service", Is that you have to override the
onStartCommand()
method which is where you receive the intent object:When you create a
Service
you should override theonStartCommand()
method so if you closely look at the signature below, this is where you receive theintent
object which is passed to it:So from an activity you will create the intent object to start service and then you place your data inside the intent object for example you want to pass a
UserID
fromActivity
toService
:When the service is started its
onStartCommand()
method will be called so in this method you can retrieve the value (UserID) from the intent object for exampleNote: the above answer specifies to get an Intent with
getIntent()
method which is not correct in context of a serviceFirst Context (can be Activity/Service etc)
You have a few options:
1) Use the Bundle from the Intent:
2) Create a new Bundle
3) Use the putExtra() shortcut method of the Intent
New Context (can be Activity/Service etc)
NOTE: Bundles have "get" and "put" methods for all the primitive types, Parcelables, and Serializables. I just used Strings for demonstrational purposes.