Mantas Čekanauskas
Mantas Čekanauskas

Reputation: 2228

Sending data from background service to activity which is current in background

Consider the scenario when user opens app and goes straight activity A. OnCreate method creates service which runs in the background.

this.StartService(new Intent(this, typeof(MyService)));

This service runs independently from activity, so if the user closes or destroys app, service still be running.

In activity A I register couple receivers via RegisterReceiver, so when something happens in my background service I update activity A via sending broadcast.

The problem I am facing is when user goes from activity A to activity B. At this time service is sending broadcast that something needs to be changed on activity A, but as it is not in a foreground, I will not will be updated via receiver. So when user goes back from activity A to activity B, user sees old data. And service does these updates in irregular intervals.

What is the proper way to update activity which was in background and then goes to foreground? What is the appropriate way to get hold of service reference or data in activity?

As I understand if I use binded services, it will be destroyed when app is killed. And I don't want that. All tutorials only shows how to update activity which is in foreground.

I'm just getting to know android, so maybe I am missing some obvious small detail.

Upvotes: 0

Views: 208

Answers (2)

isabsent
isabsent

Reputation: 3763

You can use Context#sendStickyBroadcast. It is deprecated, but still working. Your activity will get such broadcast when it goes foreground. Don't forget Context#removeStickyBroadcast after getting it.

Upvotes: 0

adarsha nayak v
adarsha nayak v

Reputation: 306

  1. You can persist your data in database or file
  2. You can restart service to fetch updated data

Upvotes: 0

Related Questions