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

时间:2015-10-26 09:44:29

标签: java android android-studio

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

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

  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来监控?除应用程序状态发生变化后通知您的方法还有其他解决方案吗?

1 个答案:

答案 0 :(得分:0)

您可以编写一个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);