2017-04-13 60 views
0

這個問題已經被問喜歡百倍運行,但所有我能罰有使用檢查,如果我的應用程序在後臺

getRunningAppProcesses() 

相同的答案不上棒棒堂

正常工作所以它有一個完全可靠的方法來知道我的應用程序是否在背景中活着?

謝謝

編輯:

這就是我用它來檢查,如果在前臺應用程序:使用

喜好:

public static void setStartingActivity(Context context, boolean isStartingActivity) { 
     PreferenceManager.getDefaultSharedPreferences(context).edit().putBoolean("isStartingActivity", isStartingActivity).apply(); 
    } 

    public static boolean isStartingActivity(Context context) { 
     return PreferenceManager.getDefaultSharedPreferences(context).getBoolean("isStartingActivity", false); 
    } 

    public static void setAppRunningInForeground(Context context, boolean isRunning) { 
     PreferenceManager.getDefaultSharedPreferences(context).edit().putBoolean("AppIsRunningInForeground", isRunning).apply(); 
    } 

    public static boolean isAppRunningForeground(Context context) { 
     return PreferenceManager.getDefaultSharedPreferences(context).getBoolean("AppIsRunningInForeground", false); 
    } 

開始活動:

Utility.PreferencesManager.setStartingActivity(getApplicationContext(), true); 
startActivity(new Intent(getApplicationContext(), MainActivity.class)); 

調用OnStop和在onStart實現:

@Override 
protected void onStart() { 
    super.onStart(); 
    Log.e("Debugging", "MainActivity onStart"); 
    Utility.PreferencesManager.setAppRunningInForeground(getApplicationContext(), true); 
} 

@Override 
protected void onStop() { 
    super.onStop(); 
    Log.e("Debugging", "MainActivity onStop"); 

    if (!Utility.PreferencesManager.isStartingActivity(getApplicationContext())) 
     Utility.PreferencesManager.setAppRunningInForeground(getApplicationContext(), false); 
    else 
     Utility.PreferencesManager.setStartingActivity(getApplicationContext(), false); 
} 
+0

您是否嘗試過[onPause](https://developer.android.com/guide/components/activities/activity-lifecycle.html#onpause) – Derek

+0

我認爲這是尋找的內容:http:// stackoverflow。 com/questions/30619349/android-5-1-1-and-above-getrunningappprocesses-returns-my-application-packag –

+0

通常,無論您在此嘗試完成什麼,都有更好的解決方案。你打算如何處理關於你是處於前景還是背景的信息? – CommonsWare

回答

0

阻止同步時,UI圍繞不會解決你的問題,僅僅是因爲用戶可以返回到你的用戶界面,而你是在一個同步的中間。你需要能夠處理這種情況。

當用戶最近進入用戶界面時避免同步,對於「最近」的短暫值,可能有助於降低用戶在同步應用程序時返回到用戶界面的機率。

根據您的意見,我們假設您的應用包含1+個活動加上您的同步適配器。當您的同步適配器運行時,您需要確定用戶最近是否已經進入用戶界面進行此過程。

有三種可能性:

  1. 的UI是在前臺當同步適配器運行

  2. 的UI是在後臺運行同步適配器運行

  3. 有沒有用戶界面,因爲您的用戶界面已被終止的最後一個進程,並且您的同步適配器在沒有用戶界面的新進程中運行

即興,來處理,我將有一個自定義Application,有兩個boolean領域:

  • areActivitiesCreated,這將是true如果這個過程在默認情況下

  • 曾經創建活動, false
  • isInBackground

    ,這將是true,如果應用程序是在後臺運行,否則false

我會有Applicationcall registerActivityLifecycleCallbacks(),並設置areActivitiesCreatedtrue在回調的onActivityCreated

我將有Application覆蓋onTrimMemory(),並更新基於傳入的內飾水平isInBackground,將其設置爲false如果修剪水平是TRIM_MEMORY_RUNNING_*值之一,或true否則。

然後,您同步適配器會繼續前進,做它的工作,如果任一areActivitiesCreatedfalse(這意味着你沒有用戶界面),或者如果isInBackgroundtrue(意思是你是不是在前臺)。

這樣可以避免將代碼添加到所有活動以跟蹤此情況。

相關問題