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

问题描述:

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

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

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

+0

这也将停用通知从该活动开始另一项活动时发送。 – 2016-07-20 18:52:32

+0

在我的项目中,我有太多的活动如何知道应用程序在后台? – 2016-12-20 03:32:10

您可以在ActivityManager中使用getRunningAppProcesses()

更新,请参阅本第一:

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" /> 
+1

我没有话...........太棒了! – GOLDEE 2013-03-13 11:44:03

+1

嗨@peceps我想告诉你,Android 4.4(或N5)这种方法无法正常工作。 topActivity和上下文包是平等的......你能否更新你的答案? – StErMi 2013-11-11 15:30:06

+0

@StErMi http://*.com/questions/3667022/android-is-application-running-in-background – Raheel 2013-12-21 08:23:41

仅用于API级14及以上

可以使用ComponentCallbacks2activityservice

实施例:

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 
    } 
    } 
}