【问题标题】:isApplicationBroughtToBackground security feature misbehaves oftenisApplicationBroughtToBackground 安全功能经常出现问题
【发布时间】:2014-02-06 06:25:38
【问题描述】:

我正在使用它来实现一项安全功能,如果我的应用在从其他应用返回后重新获得焦点,则会显示锁定屏幕。

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

在我的例子中,有问题的延迟应用是 com.android.mms 和 com.google.android.apps.maps。

我在应用程序中也有一个调用工具,但它并没有出现异常。

我对这种行为完全感到困惑。

【问题讨论】:

  • 不清楚您的问题是什么。我也不知道任何isApplicationBroughtToBackground() 方法。它来自哪里?

标签: android activity-manager


【解决方案1】:

这对于 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;
}

【讨论】:

  • 嗨。抱歉这么晚才回复。我想知道isLoggedIn的使用。请详细说明一下?
  • 这可能是特定于用例的东西。您可能有其他逻辑来确定用户是否登录。如果你认为你不需要这个,就把它扔掉。
猜你喜欢
  • 1970-01-01
  • 2018-04-21
  • 2013-04-09
  • 1970-01-01
  • 1970-01-01
  • 2012-11-03
  • 2014-04-04
  • 2021-06-13
  • 2021-03-18
相关资源
最近更新 更多