【问题标题】:Android app automatically coming to foregroundAndroid 应用程序自动进入前台
【发布时间】:2014-09-10 09:32:58
【问题描述】:

在我的应用程序中 FirstActivity Asynctask 在 asyntask 结束时调用 secondactivity 将被打开

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

如何避免?

【问题讨论】:

    标签: java android android-activity start-activity


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

      在启动第二个活动之前检查您的应用程序是否在前台,使用如下方法:

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

      【讨论】:

        【解决方案3】:

        检查是否打开了任何Activity。

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-01-06
          相关资源
          最近更新 更多