android – isApplicationBroughtToBackground安全功能经常行为不端

前端之家收集整理的这篇文章主要介绍了android – isApplicationBroughtToBackground安全功能经常行为不端前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在使用它来实现一个安全功能,如果我的应用程序从其他应用程序返回后重新获得焦点,则会显示锁定屏幕.

现在,问题是安全功能有时会显示两次.在挖掘了一下后,我注意到ActivityManager.getRunningTasks(1)中的topActivity有时仍然是您刚刚返回的活动.

就我而言,令人讨厌的挥之不去的应用程序是com.android.mms和com.google.android.apps.maps.

我在应用程序中也有一个呼叫设施,但它没有行为不端.

我对这种行为感到困惑.

解决方法

这对 Android来说确实是个问题.尝试下面对我有用的:

为您的活动准备基础课程.在里面:

@Override
protected void onPause() {
    Utils.wentInBackground(this);
    super.onPause();
}

@Override
protected void onResume() {
    Utils.wentInForeground(this);
    super.onResume();
}

然后在静态实用程序类中有这样的:

public static void wentInBackground(final Activity which) {
    inBackground = true;
    lastPaused = which.getClass().getSimpleName();

    final PowerManager powerManager = (PowerManager) which.getSystemService(POWER_SERVICE);
    final boolean isScreenOn = powerManager.isScreenOn();

    if (isApplicationSentToBackground(which) || !isScreenOn) {
        // Do your security lockdown here.
    }
}


public static boolean isApplicationSentToBackground(final Context context) {
    ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
    List<RunningTaskInfo> tasks = am.getRunningTasks(1);

    if (!tasks.isEmpty()) {
        ComponentName topActivity = tasks.get(0).topActivity;
        if (!topActivity.getPackageName().equals(context.getPackageName())) {
            return true;
        }
    }

    return false;
}


public static void wentInForeground(final Activity which) {
    inBackground = false;
    final String activityName = which.getClass().getSimpleName();

    if (lastPaused.equals(activityName) || !isLoggedIn()) {

        if (isLoggedIn()) {
             // Do your security lockdown here again,if necessary.
        }

        // Show your security screen or whatever you need to.
    }
}

public static boolean isLoggedIn() {
    return loggedIn;
}

猜你在找的Android相关文章