How to know if my app is open when I managed a pus

2019-04-28 23:39发布

问题:

Using Android, when I received a notification push throw my GCMIntentService, I want to know if my app is open or not, because if my app is open when the user click on the notification I want to do nothing, but if the app is close I want to open the app.

回答1:

Launch the root activity (the one that has ACTION=MAIN and CATEGORY=LAUNCHER in the manifest) and add Intent.FLAG_ACTIVITY_NEW_TASK. If the app is already active (no matter which activity is on top) this will just bring the task to the front. If the app isn't active, it will start it with your root activity.



回答2:

Define this in all the activities : 1.) Define a static final boolean flag named 'check_running mode' 2.) Define(override) onResume() and onPause() methods in all activities. 3.) Set the value of this falg as 'true' in onResume() and 'false' in OnPause() methods respectively. 4.) Check out when u receive the push notification : a. If falg value is true it means app is in forground so do nothing in that case b. If flag value is false it means app is in background so You can open the app in that case

NOTE: The falg must be static final as you can change it from any of the activity and access it in your receiver class simply. I hope it'll work for you!

1 :
static boolean check_running mode = false;


-------------------
2:
@Override
protected void onResume() {
    super.onResume();

    check_running mode = true;
}

@Override
protected void onPause() {
    check_running mode = false;

    super.onPause();
}

---------------------
3 :
if (check_running mode) {
    showUserView();
}
else {
    showNotification();
}


回答3:

public static boolean isAppRunning(Context context) {
    // check with the first task(task in the foreground)
    // in the returned list of tasks
    ActivityManager activityManager = (ActivityManager) context
            .getSystemService(Context.ACTIVITY_SERVICE);
    List<RunningTaskInfo> services = activityManager
            .getRunningTasks(Integer.MAX_VALUE);
    if (services.get(0).topActivity.getPackageName().toString()
            .equalsIgnoreCase(context.getPackageName().toString())) {
        // your application is running in the background
        return true;
    }
    return false;
}