Detect when Android app is going to background

前端 未结 2 1918
闹比i
闹比i 2021-01-21 20:37

In my application I need to detect whether my application is going to background or is switching to another activity of the same application... I know that I have to use the onP

相关标签:
2条回答
  • 2021-01-21 20:48
    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..).

    0 讨论(0)
  • 2021-01-21 20:48

    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

    0 讨论(0)
提交回复
热议问题