How to detect when an Android app goes to the background and come back to the foreground

后端 未结 30 1752
独厮守ぢ
独厮守ぢ 2020-11-22 00:56

I am trying to write an app that does something specific when it is brought back to the foreground after some amount of time. Is there a way to detect when an app is sent to

30条回答
  •  萌比男神i
    2020-11-22 01:11

    If your app consists of multiple activites and/or stacked activites like a tab bar widget, then overriding onPause() and onResume() will not work. I.e when starting a new activity the current activites will get paused before the new one is created. The same applies when finishing (using "back" button) an activity.

    I've found two methods that seem to work as wanted.

    The first one requires the GET_TASKS permission and consists of a simple method that checks if the top running activity on the device belongs to application, by comparing package names:

    private boolean isApplicationBroughtToBackground() {
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List tasks = am.getRunningTasks(1);
        if (!tasks.isEmpty()) {
            ComponentName topActivity = tasks.get(0).topActivity;
            if (!topActivity.getPackageName().equals(context.getPackageName())) {
                return true;
            }
        }
    
        return false;
    }
    

    This method was found in the Droid-Fu (now called Ignition) framework.

    The second method that I've implemented my self does not require the GET_TASKS permission, which is good. Instead it is a little more complicated to implement.

    In you MainApplication class you have a variable that tracks number of running activities in your application. In onResume() for each activity you increase the variable and in onPause() you decrease it.

    When the number of running activities reaches 0, the application is put into background IF the following conditions are true:

    • The activity being paused is not being finished ("back" button was used). This can be done by using method activity.isFinishing()
    • A new activity (same package name) is not being started. You can override the startActivity() method to set a variable that indicates this and then reset it in onPostResume(), which is the last method to be run when an activity is created/resumed.

    When you can detect that the application has resigned to the background it is easy detect when it is brought back to foreground as well.

提交回复
热议问题