【问题标题】:How to check if application is running on background?如何检查应用程序是否在后台运行?
【发布时间】:2020-10-28 19:03:24
【问题描述】:

我正在使用 firebase 向应用程序发送通知,并根据通知将用户定向到某些活动。到目前为止一切顺利,我遇到的问题是,如果应用程序在后台运行,则将显示的活动是主要活动,但我无法完全管理它。

我相信有几个这样的问题,但没有完全得到我正在寻找的答案。

任何帮助或建议都会很棒,谢谢

【问题讨论】:

    标签: android firebase push-notification


    【解决方案1】:

    试试

    /**Flag to determine if the Activity is visible*/
        private static boolean activityVisible;
        private static boolean activityDestroy;
    
    /**Is the application actually visible on the mobile screen*/
    public static boolean isActivityVisible(){
        return activityVisible;
    }
    
    /**Is the application actually destroyed*/
    public static boolean isActivityDestroy(){
        return activityDestroy;
    }
    
    /**Is the application actually destroyed*/
    public static void activityDestroy(boolean isDestroy){
        activityDestroy = isDestroy;
    }
    
    /**Is the application actually in the background*/
    public static boolean isActivityInBackground(){
        return !activityVisible;
    }
    
    
    /**Change the state of the Application to resume*/
    public static void activityResumed() {
        activityVisible = true;
    }
    
    /**Change the state of the Application to paused*/
    public static void activityPaused() {
        activityVisible = false;
    }
    

    然后进行检查

        Application app = ((Application)getApplicationContext());
        boolean visible = app.isActivityVisible();
    

    【讨论】:

      【解决方案2】:

      Android 10(API 级别 29)及更高版本对应用在后台运行时何时可以启动 Activity 施加了限制。这些限制有助于最大限度地减少对用户的干扰,并让用户更好地控制屏幕上显示的内容。

      【讨论】:

      • 感谢您的回复。那会有什么限制?
      【解决方案3】:

      您可以使用ActivityManagerimportance 字段。 下面是 C# 使用 Xamarin 的方法,但和 Java 很相似。

      P.S.:如果你愿意,我可以将该代码移植到 Java

          public static Importance GetAppState(Context context, string packageName)
          {
              try
              {
                  var manager = (ActivityManager)context.GetSystemService(Context.ActivityService);
      
                  var processes = manager.RunningAppProcesses;
      
                  if (processes != null)
                      foreach (var process in processes)
                          if (process.ProcessName.Equals(packageName))
                              return process.Importance;
              }
              catch
              {
              }
      
              return Importance.Gone;
          }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-03-21
        • 2017-12-31
        • 2014-10-24
        • 2017-02-04
        相关资源
        最近更新 更多