【问题标题】:android:how to check if application is running in backgroundandroid:如何检查应用程序是否在后台运行
【发布时间】:2010-07-06 06:16:24
【问题描述】:

我是安卓新手。我有基于客户端服务器的应用程序。服务器在每分钟后不断向客户端发送更新通知,在客户端,我的应用程序接收这些更新并使用 Toast 显示它。但是现在我的问题是,每当我的客户端应用程序进入后台服务器时,都会继续发送更新通知,并且我的客户端会显示它,就好像应用程序在前台一样。我不知道如何检查应用程序是否在后台运行。

【问题讨论】:

    标签: android


    【解决方案1】:

    更新,先看这个:

    Checking if an Android application is running in the background


    要检查您的应用程序是否被发送到后台,您可以在应用程序中的每个活动上调用onPause() 上的此代码:

     /**
       * Checks if the application is being sent in the background (i.e behind
       * another application's Activity).
       * 
       * @param context the context
       * @return <code>true</code> if another application will be above this one.
       */
      public static boolean isApplicationSentToBackground(final Context context) {
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<RunningTaskInfo> tasks = am.getRunningTasks(1);
        if (!tasks.isEmpty()) {
          ComponentName topActivity = tasks.get(0).topActivity;
          if (!topActivity.getPackageName().equals(context.getPackageName())) {
            return true;
          }
        }
    
        return false;
      }
    

    为此,您应该将其包含在您的AndroidManifest.xml

    <uses-permission android:name="android.permission.GET_TASKS" />
    

    【讨论】:

    【解决方案2】:

    http://developer.android.com/guide/topics/fundamentals.html#lcycles 是对 android 应用程序生命周期的描述。

    当 Activity 进入后台时,会调用 onPause() 方法。因此,您可以在此方法中停用更新通知。

    【讨论】:

    • 如果从该活动开始另一个活动,这也会停用通知发送。
    • 在我的项目中我有太多的活动如何知道应用程序在后台?
    【解决方案3】:

    仅适用于 API 级别 14 及以上

    您可以将ComponentCallbacks2 用于activityservice 等。

    例子:

    public class MainActivity extends AppCompatActivity implements ComponentCallbacks2 {
       @Override
       public void onConfigurationChanged(final Configuration newConfig) {
    
       }
    
       @Override
       public void onLowMemory() {
    
       }
    
       @Override
       public void onTrimMemory(final int level) {
         if (level == ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN) {
            // app is in background
         }
       }
    }
    

    【讨论】:

      【解决方案4】:

      您可以在 ActivityManager 中使用getRunningAppProcesses()

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-05-11
        • 1970-01-01
        • 1970-01-01
        • 2015-01-24
        • 1970-01-01
        相关资源
        最近更新 更多