android activity工具:判断activity是否在前台显示

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/jian11058/article/details/89399331

public class ActivityUtils {

    /**
     * 判断某个界面是否在前台
     *
     * @param activity 要判断的Activity
     * @return 是否在前台显示
     */
    public static boolean isForeground(Activity activity) {
        return isForeground(activity, activity.getClass().getName());
    }

    /**
     * 判断某个界面是否在前台
     *
     * @param context   Context
     * @param className 界面的类名
     * @return 是否在前台显示
     */
    public static boolean isForeground(Context context, String className) {
        if (context == null || TextUtils.isEmpty(className))
            return false;
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningTaskInfo> list = am.getRunningTasks(1);
        if (list != null && list.size() > 0) {
            ComponentName cpn = list.get(0).topActivity;
            if (className.equals(cpn.getClassName()))
                return true;
        }
        return false;
    }
}

调用的时候: if (ActivityUtils.isForeground(getContext(), ChatingActivity.class.getName())){

猜你喜欢

转载自blog.csdn.net/jian11058/article/details/89399331