简体   繁体   中英

Android app automatically coming to foreground

In my application in FirstActivity Asynctask is called at the end of asyntask secondactivity will be opened

when app is in background when asyntask is running after completion of async task Application automatically coming to foreground without any user interaction

how to avoid it?

In android we can find the app is in foreground or background like this:

ActivityManager activityManager = (ActivityManager) getApplicationContext()
.getSystemService(Activity.ACTIVITY_SERVICE);
String className = activityManager.getRunningTasks(1).get(0).topActivity
.getClassName();

if (className.equals("your activity class name with package")) {
//ToDO
}

Check if your application is in foreground before starting the second activity using a method like this:

public static boolean isApplicationSentToBackground(final Context context) {
    ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
    List<RunningTaskInfo> tasks = am.getRunningTasks(1);
    if (!tasks.isEmpty()) {
        ComponentName topActivity = tasks.get(0).topActivity;
        if (!topActivity.getPackageName().equals(context.getPackageName())) {
            return true;
        }
    }
    return false;
}

Check Whether any Activity is opened or Not.

    /***
     * Checking Whether any Activity of Application is running or not
     * @param context
     * @return
     */
    public boolean isForeground(Context context) {

        // Get the Activity Manager
        ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);

        // Get a list of running tasks, we are only interested in the last one, 
        // the top most so we give a 1 as parameter so we only get the topmost.
        List< ActivityManager.RunningTaskInfo > task = manager.getRunningTasks(1); 

        // Get the info we need for comparison.
        ComponentName componentInfo = task.get(0).topActivity;

        // Check if it matches our package name.
        if(componentInfo.getPackageName().equals(context.getPackageName())) 
            return true;

        // If not then our app is not on the foreground.
        return false;
    }

Use this like:

if(isForeground(context)) {
    //Nothing to do
} else {

    /**
          You can do here what you want to do
      **/

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM