Detect when android app go backrgound

一笑奈何 提交于 2019-12-02 01:10:05
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;
    }

UPDATE: getRunningTasks has been declared to not be guaranteed to be accurate.

Call in onStop. onStop gets called after onStart of whatever takes over the screen - if its an activity in the same apk package then you're not going into the background. This does require the GET_TASKS permission.

Or bind to a service onStart & unbind onStop - the service will then be onDestroyed when all your activities are stopped (or track binds vs unbinds if you don't want to rely on onDestroyed getting called - because it might not..).

There is no direct approach to get the app status while background or foreground, but even i have faced this issue, and found the solution with onWindowFocusChanged and onStop. For more details: http://vardhan-justlikethat.blogspot.in/2013/05/android-solution-to-detect-when-android.html

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!