android:如何检查应用程序是否在后台运行

Ris*_*ise 10 android

我是android的新手.我有基于客户端服务器的应用.服务器每隔一分钟就会继续向客户端发送更新通知,在客户端,我的应用程序会收到这些更新并使用Toast显示它.但现在我的问题是每当我的客户端应用程序进入后台服务器继续发送更新通知,我的客户端显示它就好像应用程序在前台.我没有得到如何检查该应用程序是否在后台运行.

pec*_*eps 36

更新,请先看看:

检查Android应用程序是否在后台运行


要检查您的应用程序是否已发送到后台,您可以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;
  }
Run Code Online (Sandbox Code Playgroud)

为此,你应该把它包括在你的 AndroidManifest.xml

<uses-permission android:name="android.permission.GET_TASKS" />
Run Code Online (Sandbox Code Playgroud)


nur*_*ion 8

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

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