I'm trying to start a Service
from my Activity
to look out for changes on a web page, it's a private app so I don't bother the battery life...
But I'd like to pass data from my Service
to my Activity
... I can't seem to find a way to call the Activity
from my Service
. How can I achieve this?
Build and issue the notification: Create an Intent that starts the Activity . Set the Activity to start in a new, empty task by calling setFlags() with the flags FLAG_ACTIVITY_NEW_TASK and FLAG_ACTIVITY_CLEAR_TASK . Create a PendingIntent by calling getActivity() .
Use a Handler in your service that registers a client when your ListActivity connects to the service; that is, in your onServiceConnected method in your ListActivity , send a Message to your service that enables you to keep track of connected clients.
You can start a service from an activity or other application component by passing an Intent to startService() or startForegroundService() . The Android system calls the service's onStartCommand() method and passes it the Intent , which specifies which service to start.
This example demonstrates how do I communicate between Activity and Service in android. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main. xml.
As Alex indicated, you can bind to the service and pass some sort of listener or callback to the service to use on events.
Or, you can use a broadcast Intent
, perhaps using methods like setPackage()
on the Intent
to limit the scope of the broadcast.
Or, you can use createPendingResult()
to create a PendingIntent
that you pass as an Intent
extra to the service -- the service can then use that PendingIntent
to trigger onActivityResult()
in your activity.
Or, you can use a ResultReceiver
.
Or, you can use a Messenger
.
(admittedly, I have not tried those latter two approaches, but I think they will work here)
One more alternative: if your service updates content provider, activity can be notified via ContentObserver. This would be enough if your service downloads some data from server and you simply want to display fresh contents in the activity.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With