Either show notification or react in app

I have a background service doing some work - finding user location by interval (started with startService

). Once the special condition came up, I would like to do the following:

  • If the app is in the foreground, start a specific operation.
  • If the app is not in the foreground or closed, show a notification that will start the required activity when clicked.

I know how to show notification and how the intent of a manipulator from a server with a broadcast receiver for example. But how can I tell if my application is in the foreground? Or maybe you can suggest a complete best solution?

+3


source to share


2 answers


I determine if my application is in the foreground

There are several ways to find out what's ahead, but I really prefer to track this myself (as it helps me apply additional logic when needed). Plus it's a pretty simple task. For this to happen, you need a static counter int

somewhere (you can use your object Application

if you have it, or else it doesn't really matter). In each one, Activity

onResume()

you increase the counter by one, and in each you onPause()

decrease it by one. If the counter is equal 0

, then none of your actions are in the foreground, so from your point of view, you are in the background and you are sending a notification. For simplicity, I always do this in my class ActivityBase

, all my actions are expanded.

If you don't want to track it yourself, you can use ActivityManager

to see what's currently in the 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 it requires an <uses-permission android:name="android.permission.GET_TASKS" />

entry in your manifest, so not always welcome.

+1


source


An alternative to Marcin's answers is to bind and cancel activities on a service. This will allow communication between the Service and the activity as long as this binding exists, and the Service will know if an activity capable of handling the script is currently available. you may not want to start the action directly if the user is in the middle of some important process (for example, accepts a T & Cs / EULA or something else), so the service can tell the Action that an event has occurred, but the action can respond correctly to event.



0


source







All Articles