8

I am using this to implement a security feature that displays a locking screen if my app regains the focus after coming back from a different app.

Now, the problem is that the security feature is sometimes shown twice. After digging around a bit I noticed that the topActivity from ActivityManager.getRunningTasks(1) is sometimes still the activity you just returned from.

In my case, the offending lingering apps are com.android.mms and com.google.android.apps.maps.

I have a calling facility as well within the application but it is not misbehaving.

I am completely baffled with this behavior.

android developer
  • 1,253
  • 2
  • 13
  • 43
  • It is not really clear what your question is. Also I don't know of any `isApplicationBroughtToBackground()` method. Where does it come from? – nicopico Feb 11 '14 at 13:23

1 Answers1

0

This is really a problematic case with Android. Try the following which worked for me:

Have a base class for your activities. In it:

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

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

Then in a static utilities class have this:

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;
}
Stan
  • 2,151
  • 1
  • 25
  • 33
  • Hi. Sorry for replying so late. I want to know the use of isLoggedIn. Will you please elaborate? – android developer Mar 11 '14 at 15:47
  • This is probably something specific for the use case. You may have other logic for determining whether the user is logged in or not. If you don't think you need this just drop it. – Stan Mar 13 '14 at 15:51