androidandroid-intentservicedata-transferpass-data

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?


Solution

  • 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.