【问题标题】:How to know if my application is in foreground or background, android?如何知道我的应用程序是在前台还是后台,android?
【发布时间】:2015-01-08 21:22:38
【问题描述】:

我需要检查我的应用程序是在后台运行还是在前台运行,然后执行一些相对于它的操作。

我搜索了很多,没有明确的解决方案。

  1. 在其 onPause() 和 onResume() 方法中创建一个父活动,保留一些变量以相应地更新它们。当您创建任何新活动时,继承您的父活动。 虽然这是我觉得完成任务的最佳解决方案,但有时如果即使应用程序在后台单击电源按钮,也会调用它的 onResume()。

  2. 使用 GETTASKS 权限 - 这个解决方案也不错。但它只能用于调试目的。如果您想将您的应用放到 Google Play 商店中,则不需要。

Get Running Taks

还有其他首选的解决方案吗?

【问题讨论】:

    标签: android android-activity background task foreground


    【解决方案1】:

    这解决了我的问题:

      private boolean isAppOnForeground(Context context,String appPackageName) {
        ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningAppProcessInfo> appProcesses = activityManager.getRunningAppProcesses();
        if (appProcesses == null) {
            return false;
        }
        final String packageName = appPackageName;
        for (ActivityManager.RunningAppProcessInfo appProcess : appProcesses) {
            if (appProcess.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND && appProcess.processName.equals(packageName)) {
     //                Log.e("app",appPackageName);
                return true;
            }
        }
        return false;
    }
    

    【讨论】:

      【解决方案2】:

      原答案:https://stackoverflow.com/a/60212452/10004454 根据 Android 文档推荐的方法是

      class MyApplication : Application(), LifecycleObserver {
      
      override fun onCreate() {
          super.onCreate()
          ProcessLifecycleOwner.get().lifecycle.addObserver(this);
      }
      
      fun isActivityVisible(): String {
          return ProcessLifecycleOwner.get().lifecycle.currentState.name
      }
      
      @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
      fun onAppBackgrounded() {
          //App in background
      
          Log.e(TAG, "************* backgrounded")
          Log.e(TAG, "************* ${isActivityVisible()}")
      }
      
      @OnLifecycleEvent(Lifecycle.Event.ON_START)
      fun onAppForegrounded() {
      
          Log.e(TAG, "************* foregrounded")
          Log.e(TAG, "************* ${isActivityVisible()}")
          // App in foreground
      }}
      

      在您的 gradle(应用程序)中添加:implementation "androidx.lifecycle:lifecycle-extensions:2.2.0"

      然后在运行时检查状态调用MyApplication().isActivityVisible()

      【讨论】:

        【解决方案3】:

        使用AppVisibilityDetector,我实现了这个类来检测应用可见性状态。它可以检测前台和后台状态并执行回调方法。

         AppVisibilityDetector.init(MyApp.this, new AppVisibilityCallback() {
            @Override
            public void onAppGotoForeground() {
                //app is from background to foreground
            }
            @Override
            public void onAppGotoBackground() {
                //app is from foreground to background
            }
        });
        

        MyApp 是您的应用程序类

        public class MyApp extends Application { ... }
        

        您不需要在 Activity 中添加一些其他代码或在 AndroidManifest.xml 中添加任何权限

        【讨论】:

          【解决方案4】:

          您可以使用流程生命周期所有者进行检查。

          fun isAppOnForeground(): Boolean {
          return ProcessLifecycleOwner.get().getLifecycle().getCurrentState()
              .isAtLeast(Lifecycle.State.STARTED);
          }
          

          【讨论】:

          • 谢谢你,这是一个正确的解决方案,而不是使用 ActivityManager.getMyMemoryState(appProcessInfo),因为我看到它在某些设备上无法正常工作。
          【解决方案5】:

          您可以使用此代码获取您的应用的前台运行状态(true

          public boolean isAppForground(Context mContext) {
              ActivityManager am = (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
              List<RunningTaskInfo> tasks = am.getRunningTasks(1);
              if (!tasks.isEmpty()) {
                  ComponentName topActivity = tasks.get(0).topActivity;
                  if (!topActivity.getPackageName().equals(mContext.getPackageName())) {
                      return false;
                  }
              }
              return true;
          }
          

          【讨论】:

          • 这需要 GET_TASKS 权限,根据问题中的第 2 点,这不是一个有效的答案。
          【解决方案6】:

          使用以下函数检查您的应用程序是在后台还是前台

              public static Boolean getProcessState(Context mContext) {
              ActivityManager am = (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
          
              boolean noProcessOnForeground = true;
              boolean isProcessForeground = false;
          
              System.out.println("Checking if process: " + mContext.getApplicationInfo().processName + " is Foreground or Background");
              List<ActivityManager.RunningAppProcessInfo> current_processes = am.getRunningAppProcesses();
              for (ActivityManager.RunningAppProcessInfo appProcess : current_processes) {
                  if (appProcess.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
          
                      noProcessOnForeground = false;
                      if ((mContext.getApplicationInfo().processName).equalsIgnoreCase(appProcess.processName)) {
          
                          isProcessForeground = true;
                          System.out.println("Process is Foreground");
                          break;
                          //   Toast.makeText(getApplicationContext(), "Process is Foreground", Toast.LENGTH_SHORT).show();
                      } else {
          
          
                          System.out.println("Process is Background");
                          //    Toast.makeText(getApplicationContext(), "Process is Background", Toast.LENGTH_SHORT).show();
                          isProcessForeground = false;
                          break;
                      }
                  }
              }
          
              if (noProcessOnForeground) {
          
                  System.out.println("there is no process on foreground so setting " + mContext.getApplicationInfo().processName + " as background");
                  isProcessForeground = false;
              }
          
              return isProcessForeground;
          }
          

          【讨论】:

            【解决方案7】:

            只想在 Activity/Fragment 中使用以下代码:

            final boolean isAlive = AppVisibilityHelper.isForeground(HomeActivity.this);
            

            想制作一个像下面这样的类:

             public class AppVisibilityHelper{
            
                    public static boolean isForeground(final Context context) {
                        final String packageName = "com.acb.android";
                        ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
                        List<ActivityManager.RunningTaskInfo> runningTaskInfo = manager.getRunningTasks(1);
                        ComponentName componentInfo = runningTaskInfo.get(0).topActivity;
                        return componentInfo.getPackageName().equals(packageName);
                    }
                }
            

            如果您想每隔一秒检查一次,请在 Activity 中使用以下代码:

             Runnable CheckAppIsRunning = new Runnable() {
                    @Override
                    public void run() {
                       final boolean isAlive = AppVisibilityHelper.isForeground(HomeActivity.this);
                            if (isAlive) {
                                // App is running
                            } else {
                                // App is not running
                            }
                        }
                        appIsRuningHandler.postDelayed(CheckAppIsRunning, 1000);
                    }
                };
            

            在 onCreate() 中只调用一次:

            appIsRuningHandler.postDelayed(CheckAppIsRunning, 1000);
            

            【讨论】:

              【解决方案8】:

              检查应用处于前台状态还是后台状态

              ActivityManager activityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
                 List<ActivityManager.RunningAppProcessInfo> appProcesses = activityManager.getRunningAppProcesses();
              
                 final String packageName = getPackageName();
                  for (ActivityManager.RunningAppProcessInfo appProcess : appProcesses)
                 {
              
                 if (appProcess.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND && appProcess.processName.equals(packageName))
                    {
              
                     //if app in background state this will execute
              
                      Intent intent = getPackageManager().getLaunchIntentForPackage("hinditextonphoto.com.allcomponents");
                      startActivity(intent);
                      System.out.println("bbbbbbbbbbbbb    background");
                    }
              
                     else if (appProcess.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND && appProcess.processName.equals(packageName))
                     {
              
                     //if app in forground state this will execute
                       System.out.println("bbbbbbbbbbbbb    forground");
              
                     }
              
                }
              

              【讨论】:

              • 伙计们使用此代码来检查应用程序是处于前台状态还是后台状态,您将准确无误!保持摇滚!........
              • 注意:当使用BroadcastReceiverService 时,当应用在后台时appProcess.importance 的值为300IMPORTANCE_SERVICE
              【解决方案9】:

              您可以使用ActivityManager.RunningAppProcessInfo 类查看应用状态。

              public boolean isForegrounded() {
                  ActivityManager.RunningAppProcessInfo appProcessInfo = new ActivityManager.RunningAppProcessInfo();
                  ActivityManager.getMyMemoryState(appProcessInfo);
                  return (appProcessInfo.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND ||
                          appProcessInfo.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_VISIBLE);
              }
              

              【讨论】:

                猜你喜欢
                • 1970-01-01
                • 2011-05-02
                • 2011-10-18
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 2014-10-24
                • 1970-01-01
                相关资源
                最近更新 更多