繁体   English   中英

Android应用程序自动进入前台

[英]Android app automatically coming to foreground

在我的FirstActivity应用程序中,异步任务结束时调用了Asynctask,secondactivity将被打开

当应用程序在后台运行时,异步任务完成后运行asyntask时,应用程序自动进入前台,而无需任何用户交互

如何避免呢?

在android中,我们可以找到该应用位于前景或背景,如下所示:

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
}

在开始第二个活动之前,请使用以下方法检查应用程序是否处于前台:

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;
}

检查是否打开了任何活动。

    /***
     * 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;
    }

像这样使用:

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

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

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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