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

后端 未结 30 1981
独厮守ぢ
独厮守ぢ 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条回答
  •  生来不讨喜
    2020-11-22 01:15

    Edit 2: What I've written below will not actually work. Google has rejected an app that includes a call to ActivityManager.getRunningTasks(). From the documentation, it is apparent that this API is for debugging and development purposes only. I'll be updating this post as soon as I have time to update the GitHub project below with a new scheme that uses timers and is almost as good.

    Edit 1: I've written up a blog post and created a simple GitHub repository to make this really easy.

    The accepted and top rated answer are both not really the best approach. The top rated answer's implementation of isApplicationBroughtToBackground() does not handle the situation where the Application's main Activity is yielding to an Activity that is defined in the same Application, but it has a different Java package. I came up with a way to do this that will work in that case.

    Call this in onPause(), and it will tell you if your application is going into the background because another application has started, or the user has pressed the home button.

    public static boolean isApplicationBroughtToBackground(final Activity activity) {
      ActivityManager activityManager = (ActivityManager) activity.getSystemService(Context.ACTIVITY_SERVICE);
      List tasks = activityManager.getRunningTasks(1);
    
      // Check the top Activity against the list of Activities contained in the Application's package.
      if (!tasks.isEmpty()) {
        ComponentName topActivity = tasks.get(0).topActivity;
        try {
          PackageInfo pi = activity.getPackageManager().getPackageInfo(activity.getPackageName(), PackageManager.GET_ACTIVITIES);
          for (ActivityInfo activityInfo : pi.activities) {
            if(topActivity.getClassName().equals(activityInfo.name)) {
              return false;
            }
          }
        } catch( PackageManager.NameNotFoundException e) {
          return false; // Never happens.
        }
      }
      return true;
    }
    

提交回复
热议问题