Mars
Mars

Reputation: 4307

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?

Upvotes: 43

Views: 33189

Answers (4)

Juozas Kontvainis
Juozas Kontvainis

Reputation: 9597

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.

Upvotes: 3

vvsueprman
vvsueprman

Reputation: 143

Some ugly ways:

1.) If the activity has not started yet, then use intent and startActivity, but remember intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

2.) Otherwise if the activity has started already, you can write your own callback method in the activity and register the method in the service, then direct call the method in the service.

Hope to find some smart way.

I think broadcast also work well, you can write a static inner class for receive broadcast and start activity. But it is also ugly in my opinion.

Upvotes: 1

Nikhil_Katre
Nikhil_Katre

Reputation: 554

The ResultReceiver mechanism has been explained in another post :- Restful API service However it would not work in all cases. Please refer to my comment on that post. The limited scope broadcast or PendingIntent mechanism seem more suitable.

Upvotes: 0

CommonsWare
CommonsWare

Reputation: 1006584

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)

Upvotes: 48

Related Questions