Crosswind
Crosswind

Reputation: 1045

Determine if my app is in the foreground

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!

Upvotes: 1

Views: 4754

Answers (1)

tohid
tohid

Reputation: 119

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
    }

Upvotes: 1

Related Questions