Android应用前后台监听最简单的方法

public class IsForeBackGroundActivityCallback implements ActivityLifecycleCallbacks {
    private int foregroundActivities = 0;
    private boolean isbackGroudAcitvity;

    @Override
    public void onActivityCreated(Activity activity, Bundle bundle) {
        if (bundle != null) { // 若bundle不为空则程序异常结束
            // 重启整个程序
            Intent intent = new Intent(activity, SplashActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK );
            startActivity(intent);
        }
    }

    @Override
    public void onActivityStarted(Activity activity) {
        LogUtils.e("栈顶的activity======"+activity);
        foregroundActivities++;
        if (foregroundActivities == 1 && !isChangingConfiguration) {
            // 应用切到前台
           
            LogUtils.e("应用切换到前台");
        
        isbackGroudAcitvity= false;
    }

    @Override
    public void onActivityResumed(Activity activity) {

    }

    @Override
    public void onActivityPaused(Activity activity) {

    }

    @Override
    public void onActivityStopped(Activity activity) {
        foregroundActivities--;
        if (foregroundActivities == 0) {
            // 应用切到后台
            LogUtils.e("应用切换到后台");
          
       
        isbackGroudAcitvity= activity.isChangingConfigurations();
    }

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

    }

    @Override
    public void onActivityDestroyed(Activity activity) {

    }
}

废话不多说,直接使用:在Application 的onCreate方法注册:

registerActivityLifecycleCallbacks(new IsForeBackGroundActivityCallback ());

就这么简单。

你可能感兴趣的:(android,android,studio,java)