判断activity和fragment是否可见

1、判断activity在前台还是后台

public static boolean isAPPBroughtToBackground(final Context context) {
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List tasks = am.getRunningTasks(1);
        if (!tasks.isEmpty()) {
            ComponentName topActivity = tasks.get(0).topActivity;
            if (topActivity.getClassName().equals(context.getClass().getName())) {
                LogUtils.e("前台");
                return true;
            }else{
                LogUtils.e("后台");
            }
        }
        return false;
    }

2、判断fragment是否可见
最初用上面的方法来判断fragemnt在前端还是后端,发现fragment永远在前端,因为fragment依附于activity存在,最终发现fragment有onHiddenChanged方法可以判断是否可见,然后根据声明的mUserVisibleHint值可判断

 private boolean mUserVisibleHint = true; //当前fragment是否可见
 @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (hidden) {
            mUserVisibleHint = false;
            LogUtils.e("不可见");
        } else {
            mUserVisibleHint = true;
            LogUtils.e("可见");
        }
    }

你可能感兴趣的:(android)