如何识别appk在Kitkat(4.4)中的背景?

时间:2013-12-10 16:54:52

标签: android android-activity android-4.4-kitkat

我正在尝试在应用程序进入后台时检测到它。一切都很完美,但在New Android Version 4.4(Kitkat)它不起作用。我无法找出Kitkat的问题。它总是返回false

public static boolean inBackground(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;
}

2 个答案:

答案 0 :(得分:2)

覆盖Activity.onPause()或Activity.onStop(),具体取决于您想要的背景级别。

答案 1 :(得分:2)

我遇到了同样的问题。解决方案是在onStop()上调用此方法。

为了简化,我将应用程序转到下面的课程时将我需要检测的活动扩展。

public abstract class MyActivity extends Activity {

    @Override
    public void onStop() {

        super.onStop();

        if (isApplicationSentToBackground(this)){

            // handle app going into background here
        }
    }

    private 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;
    }
}