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性能优化——之控件的优化 前面讲了图像的优化,接下...
前言 上一篇已经讲了如何实现textView中粗字体效果,里面主要...
最近项目重构,涉及到了数据库和文件下载,发现GreenDao这个...
WebView加载页面的两种方式 一、加载网络页面 加载网络页面,...
给APP全局设置字体主要分为两个方面来介绍 一、给原生界面设...
前言 最近UI大牛出了一版新的效果图,按照IOS的效果做的,页...