2010-07-06 203 views
9

我是Android新手。我有客戶端服務器的應用程序。服務器在每分鐘後都會繼續向客戶端發送更新通知,並且在客戶端,我的應用程序會接收這些更新並使用Toast顯示它。但現在我的問題是每當我的客戶端應用程序進入後臺服務器不斷髮送更新通知,我的客戶端顯示它,就好像應用程序在前臺。我沒有得到如何檢查應用程序在後臺運行。android:如何檢查應用程序是否在後臺運行

回答

8

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

36

更新,請參閱本第一:

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://stackoverflow.com/questions/3667022/android-is-application-running-in-background – Raheel 2013-12-21 08:23:41

2

僅用於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 
    } 
    } 
} 
相關問題