1

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?

  • You can use the [Lifecycle Aware](https://developer.android.com/topic/libraries/architecture/lifecycle) functionality – tomerpacific Jun 12 '22 at 05:09
  • @tomerpacific Do I need to use android.arch (https://www.talentica.com/blogs/android-life-cycle-aware-components/) library as this tutorial suggests. – Albert Einstien Jun 12 '22 at 05:21
  • I don't know why you went to a tutorial instead of the documentation link I sent. In the documentation itself, there is a link that shows how to add the android.lifecycle dependency. [Link](https://developer.android.com/jetpack/androidx/releases/lifecycle#declaring_dependencies). – tomerpacific Jun 12 '22 at 05:33
  • @tomerpacific Can you please provide an implementation of Lifecycle Aware? – Albert Einstien Jun 12 '22 at 09:12
  • How large is this data? – David Wasser Jun 15 '22 at 11:50
  • @DavidWasser Less than 50KB – Albert Einstien Jun 15 '22 at 12:01
  • See my answer. you could write the data to a file, put it in SQLite database, or even keep it in memory in a `public static` variable if you want to. Depends on the level of persistency you need and other factors. – David Wasser Jun 15 '22 at 12:04

2 Answers2

0

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;
0

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.

David Wasser
  • 93,459
  • 16
  • 209
  • 274