安卓判断APP是在前台还是在后台

朴灿烈づ我的快乐病毒、 2024-02-18 22:55 114阅读 0赞

安卓中判断APP是否在前台:

方法一:CCApplication 中判断

  1. private boolean mIsInForeground = false;
  2. public boolean isInForeground() {
  3. return mIsInForeground;
  4. }
  5. private class CCActivityLifecycleCallbacks implements ActivityLifecycleCallbacks {
  6. @Override
  7. public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
  8. }
  9. @Override
  10. public void onActivityStarted(Activity activity) {
  11. MonkeyLog.d(TAG, "onActivityStarted :" + activity);
  12. }
  13. @Override
  14. public void onActivityResumed(Activity activity) {
  15. mIsInForeground = true;//APP在前端
  16. Adjust.onResume();
  17. setCurrentActivity(activity);
  18. }
  19. @Override
  20. public void onActivityPaused(Activity activity) {
  21. mIsInForeground = false;//APP 在后台
  22. Adjust.onPause();
  23. setCurrentActivity(null);
  24. }
  25. @Override
  26. public void onActivityStopped(Activity activity) {
  27. }
  28. @Override
  29. public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
  30. }
  31. @Override
  32. public void onActivityDestroyed(Activity activity) {
  33. }
  34. }

在APPlication的onCreate()方法中:

  1. registerActivityLifecycleCallbacks(new CCActivityLifecycleCallbacks());

使用的时候直接判断:

  1. if (!CCApplication.getInstance().isInForeground()) {
  2. //ToDo
  3. }

方法二:

在BaseActivity中

  1. // 当前app是否是前台状态
  2. private static boolean isActive = false;

在BaseActivity 的onResume()方法中:

  1. @Override
  2. protected void onResume() {
  3. super.onResume();
  4. if (!isActive) {
  5. //app 从后台唤醒,进入前台
  6. isActive = true;
  7. }
  8. }

在onStop()方法中:

  1. @Override
  2. protected void onStop() {
  3. super.onStop();
  4. if (!isAppOnForeground()) {
  5. //app 进入后台
  6. isActive = false
  7. }
  8. }
  9. /**
  10. * 程序是否在前台运行
  11. *
  12. * @return
  13. */
  14. private boolean isAppOnForeground() {
  15. // Returns a list of application processes that are running on the device
  16. ActivityManager activityManager = (ActivityManager) getApplicationContext().getSystemService(Context.ACTIVITY_SERVICE);
  17. String packageName = getApplicationContext().getPackageName();
  18. List<ActivityManager.RunningAppProcessInfo> appProcesses = activityManager
  19. .getRunningAppProcesses();
  20. if (appProcesses == null)
  21. return false;
  22. for (ActivityManager.RunningAppProcessInfo appProcess : appProcesses) {
  23. // The name of the process that this object is associated with.
  24. if (appProcess.processName.equals(packageName)
  25. && appProcess.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
  26. return true;
  27. }
  28. }
  29. return false;
  30. }

这样就可以判断APP是在前台还是在后台了

常用的地方是当接收到Notification消息时,当APP在前端直接处理消息 当APP在后台时 将Notification消息显示在手机的消息栏中

个人GitHub地址:https://github.com/HuaDanJson

发表评论

表情:
评论列表 (有 0 条评论,114人围观)

还没有评论,来说两句吧...

相关阅读