安卓开发中判断APP在前端还是在后台

1.在自己的APPlication中定义一个int 类型的变量

private int activityCount;

2.在APPlication创建一个内部类 实现

ActivityLifecycleCallbacks
private class CCActivityLifecycleCallbacks implements ActivityLifecycleCallbacks {

    @Override
    public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
    }

    @Override
    public void onActivityStarted(Activity activity) {
        activityCount++;
    }

    @Override
    public void onActivityResumed(Activity activity) {
      
    }

    @Override
    public void onActivityPaused(Activity activity) {
       
    }

    @Override
    public void onActivityStopped(Activity activity) {
        activityCount--;
    }

    @Override
    public void onActivitySaveInstanceState(Activity activity, Bundle outState) {

    }

    @Override
    public void onActivityDestroyed(Activity activity) {

    }
}

onActivityStarted()回调中activityCount++; 

在 onActivityStopped()中activityCount--;

3.在APPlication的onCreate()方法中

registerActivityLifecycleCallbacks(new CCActivityLifecycleCallbacks());

4.在APPLication中添加一个共工的方法供外面调用:

public boolean isInForeground() {
    return (activityCount > 0);
}

5.在用到的地方就可以用自定义的APPlication的实例去调用了

个人GitHub账号:https://github.com/HuaDanJson

你可能感兴趣的:(安卓开发中判断APP在前端还是在后台)