Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Either show notification or react in application

Tags:

java

android

I have a background service doing some work - retrieving user location by interval (launched with startService). As soon special condition reached I'd like to do the following:

  1. If application is in foreground then start specific activity.
  2. If application is not in foreground or closed then show the notification that will start required activity on tap.

I know how to show notification and how handle intent from server with broadcast receiver for example. But how can I determint if my application is in foreground? Or may be you can suggest complete better solution?

like image 228
Sergey Metlov Avatar asked May 02 '26 11:05

Sergey Metlov


1 Answers

I determint if my application is in foreground

There's couple of ways to find out what is in front, but I actually prefer to track this myself (as this helps me apply additional logic if needed). Plus it's pretty simple task. To make this happen you need static int based counter somewhere (you can use your Application object if you have one, or have it elsewhere, does not really matter). In each Activity's onResume() you increment the counter by one, and in onPause() you decrement it by one. If counter equals 0 then none of your activities is in foreground so from your perspective you are in background and you post notification. For simplicity I always do that in my ActivityBase class all my activities extend.

If you do not want to track it yourself, you can use ActivityManager to see what's currently in foreground:

public boolean isAppInForeground() {
    ActivityManager am = (ActivityManager)getSystemService(Context.ACTIVITY_SERVICE);
    List<RunningTaskInfo> services = am.getRunningTasks(Integer.MAX_VALUE);

    return (services.get(0).topActivity.getPackageName().toString()
                        .equalsIgnoreCase(getPackageName().toString()));
 }

but this requires <uses-permission android:name="android.permission.GET_TASKS" /> entry in your Manifest, so not always welcome.

like image 173
Marcin Orlowski Avatar answered May 03 '26 23:05

Marcin Orlowski



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!