当前位置: 代码迷 >> Android >> 如何监视我的应用程序是否从前台运行切换到后台运行,反之亦然?
  详细解决方案

如何监视我的应用程序是否从前台运行切换到后台运行,反之亦然?

热度:24   发布时间:2023-08-04 12:06:22.0

我想通知我我的应用程序在前台运行和后台运行之间切换,反之亦然。

我得到以下代码来检测我的应用程序是否在后台运行:

  private boolean isAppIsInBackground(Context context) {
    boolean isInBackground = true;
    ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
    if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT_WATCH) {
      List<ActivityManager.RunningAppProcessInfo> runningProcesses = am.getRunningAppProcesses();
      for (ActivityManager.RunningAppProcessInfo processInfo : runningProcesses) {
        if (processInfo.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
          for (String activeProcess : processInfo.pkgList) {
            if (activeProcess.equals(context.getPackageName())) {
              isInBackground = false;
            }
          }
        }
      }
    } else {
      List<ActivityManager.RunningTaskInfo> taskInfo = am.getRunningTasks(1);
      ComponentName componentInfo = taskInfo.get(0).topActivity;
      if (componentInfo.getPackageName().equals(context.getPackageName())) {
        isInBackground = false;
      }
    }

    return isInBackground;
  }

这可能有效,但是我需要在状态更改时调用该函数的工具。 我可以做这样的事情:

BroadcastReceiver appStateReceiver = new BroadcastReceiver() {
  @Override
  public void onReceive(Context context, Intent intent) {
    Log.d("TEST", "appStateReceiver: "+isAppIsInBackground(context));
  }

};

现在,我需要以某种方式注册上述广播接收器:

IntentFilter appStateFfilter = // ???? this is the part I do not know about
context.registerReceiver(appStateReceiver, appStateFfilter);

我不会使用onPause()onResume()因为我应该在每个活动中都这样做。

如何注册BroadcastReceiver来监视应用程序是否切换状态(即在前台运行,在后台运行)? 除了我的方法之外,还有其他解决方案可以在应用程序状态更改时通知您吗?

您可以编写一个Service类来监视您的应用程序是在前台运行还是在后台运行,并可以从那里注册BroadcastReciever

private boolean isAppIsInBackground(Context context) {
    isInBackground = true;
    ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
    if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT_WATCH) {
        List<ActivityManager.RunningAppProcessInfo> runningProcesses = am.getRunningAppProcesses();
        for (ActivityManager.RunningAppProcessInfo processInfo : runningProcesses) {
            if (processInfo.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
                for (String activeProcess : processInfo.pkgList) {
                    if (activeProcess.equals(context.getPackageName())) {
                         Handler mmHandler = new Handler(getMainLooper());
                        mmHandler.post(new Runnable() {
                            @Override
                            public void run() {
                                //code
                                }
                            });
                        isInBackground = false;
                    }
                }
            }
        }
    } else {
        List<ActivityManager.RunningTaskInfo> taskInfo = am.getRunningTasks(1);
        ComponentName componentInfo = taskInfo.get(0).topActivity;
        if (componentInfo.getPackageName().equals(context.getPackageName())) {
            isInBackground = false;
            Handler mmHandler = new Handler(getMainLooper());
                mmHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        //code
                        }
                    });
        }
    }

    return isInBackground;
}

如果您的应用程序在后台运行,则此方法返回true。 在您的Service类中编写此方法,并相应地使用返回值。

为您的BroadCastReceiver执行此操作:

  Intent broadcastIntent = new Intent(); 
                                        broadcastIntent.setAction(com.example.intent.action.MESSAGE_PROCESSED); 
                                        broadcastIntent.addCategory(Intent.CATEGORY_DEFAULT); 
                                        sendBroadcast(broadcastIntent);
  相关解决方案