当Android应用程序进入后台时检测

问题描述 投票:2回答:2

在我的应用程序中,我需要检测我的应用程序是要在后台运行还是要切换到同一应用程序的另一个活动...我知道我必须使用onPause方法...但是如何区分这两种情况?

android activity-lifecycle
2个回答
8
投票
private static boolean isApplicationGoingToBackground(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;
    }

0
投票

[没有直接的方法可以在后台或前台获取应用程序状态,但是即使我也遇到了此问题,并使用onWindowFocusChanged和onStop找到了解决方案。有关更多详细信息:http://vardhan-justlikethat.blogspot.in/2013/05/android-solution-to-detect-when-android.html

© www.soinside.com 2019 - 2024. All rights reserved.