1

I have an IntentService that is refreshing data from a server (no push notifications) once an hour. If there's any new data it's supposed to either update the interface when inside the app or send a notification when my app is not in the foreground. My question would be: How do I determine which app is running in the foreground or easier if my app is running in the foreground? I don't need to know what Activity that is just the general package name of my app is totally fine!

Two things I've found so far which I'd oppose to use:

  1. ActivityManager.getRunningTasks() - it's been deprecated and as mentioned by Google might break in the future
  2. UsageStats - Seems nice but it's really inconvenient if the user has to give my app UsageStats rights.

I'm a little bit confused why I'm not able to find a solution for that..I thought this wasn't a unusual practice or whatever.

Thanks!

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
Crosswind
  • 940
  • 1
  • 10
  • 26
  • 1
    Possible duplicate of [Checking if an Android application is running in the background](http://stackoverflow.com/questions/3667022/checking-if-an-android-application-is-running-in-the-background) – OneCricketeer Mar 01 '16 at 15:43
  • Possible duplicate of [How can I tell if Android app is running in the foreground?](http://stackoverflow.com/questions/5504632/how-can-i-tell-if-android-app-is-running-in-the-foreground) – Saman Salehi Oct 26 '16 at 05:31
  • 1
    Google Solution here: https://stackoverflow.com/a/48767617/1269737 – StepanM Feb 13 '18 at 13:12

1 Answers1

1

you can solve your problem in easy way, but this work to your own package and service

1 : in your main Activity define boolean variable
2: in onCreate methode of your Main Activity change the value of variable to true
3: in Ondestroy metheo change it to false

public class MainActivity extends AppCompatActivity {
public static boolean appStatus = false;

@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

    appStatus = true;//fill the variable true : app is running
    setContentView(R.layout.activity_main);

}


@Override
protected void onDestroy() {
    super.onDestroy();//fill the variable false : app is not running
    appStatus = false;
}

}

4: in your service you can check it everywhere you want

    if(MainActivity.appStatus )
    {
        ......yourCode
    }
tohid
  • 119
  • 1
  • 7