Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Notify activity from service

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?

like image 378
Mars Avatar asked Nov 06 '10 01:11

Mars


People also ask

How do you notify activity of a service?

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() .

How can a service notify an activity of an event happening?

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.

Can you start an activity from a service?

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.

How do you communicate between service and activity?

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.


2 Answers

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)

like image 125
CommonsWare Avatar answered Sep 17 '22 19:09

CommonsWare


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.

like image 40
Juozas Kontvainis Avatar answered Sep 17 '22 19:09

Juozas Kontvainis