Albert Einstien
Albert Einstien

Reputation: 13

Check if activity is active, and if active pass data from service to activity?

I have a service called EventReceivingSevice which will get new data in onDataRefresh(JSONObject data) function.

private void onNewData(JSONData data) {
    boolean isActive=isActivityActive(); //Check if activity is active
    if(isACtive)
         passData(data);
    else
         storeData(data);
}

An activity called HomeActivity will display the data. When EventReceivingService will get new data, it has to be checked if HomeActivity is active, it has to pass the data to HomeActivity, and if not it will store the data somewhere so that HomeActivity will later use that.

The data is in JSON format.

How can achieve this?

Upvotes: 1

Views: 88

Answers (2)

David Wasser
David Wasser

Reputation: 95626

You can't reliably determine if an Activity is active. What you should do is to store the data somewhere (file, SQLite database, etc.), and then send a broadcast Intent that means "new data is available". Your Activity can register a listener that will get triggered by that broadcast Intent if the Activity is alive when the broadcast Intent is sent. It can then pick up the data from wherever you put it and do whatever you want with it.

Upvotes: 0

Shenal Akalanka
Shenal Akalanka

Reputation: 84

There is a simple method but it doesn't require JSON data. you can just add data as public static data.

public static int GRID_COUNT = 2;

If you are using that data for reading purposes, you can do it like this.

public static final int GRID_COUNT = 2;

Upvotes: 0

Related Questions