如何检查Android应用程序是在后台运行还是在前台运行?

时间:2017-05-04 10:03:49

标签: android

例如,我在我的项目中有这个代码:

   public class Utilities extends Application
{
    private static int stateCounter;

    public void onCreate()
    {
        super.onCreate();
        stateCounter = 0;
    }

    /**
     * @return true if application is on background
     * */
    public static boolean isApplicationOnBackground()
    {
        return stateCounter == 0;
    }

    //to be called on each Activity onStart()
    public static void activityStarted()
    {
        stateCounter++;
    }

    //to be called on each Activity onStop()
    public static void activityStopped()
    {
        stateCounter--;
    } 
}

但在ios中检测状态很简单:

let state: UIApplicationState = UIApplication.sharedApplication().applicationState // or use  let state =  UIApplication.sharedApplication().applicationState

if state == .Background {

// background
}
else if state == .Active {

// foreground
}

我正在搜索android是否有其他解决方案来进行此测试?

3 个答案:

答案 0 :(得分:5)

在应用程序类中编写此方法,并在任何地方使用。

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

创建一个新类baseActivity

public class BaseActivity extends AppCompatActivity {

static Boolean IsResumecalled = false;


@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

}

@Override
protected void onResume() {
    super.onResume();
    if (!IsResumecalled) {
        //call api here
    IsResumecalled= true;
    }
}

@Override
protected void onStop() {
    super.onStop();
    if (Myapplication.getInstance().isApplicationBroughtToBackground()) {
      //call api here
       IsResumecalled= false;
    }
}

}

并使用BaseActivity扩展每个活动类

答案 1 :(得分:2)

private boolean isAppOnForeground(Context context) {
        ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningAppProcessInfo> appProcesses = activityManager.getRunningAppProcesses();
        if (appProcesses == null) {
            return false;
        }
        final String packageName = context.getPackageName();
        for (ActivityManager.RunningAppProcessInfo appProcess : appProcesses) {
            Log.d(TAG, "isAppOnForeground: " + appProcess.processName);
            if (appProcess.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND && appProcess.processName.equals(packageName)) {
                return true;
            }
        }
        return false;
    }
}

答案 2 :(得分:1)

尝试使用Lifecycle的{​​{1}}方法。

currentState