2012-07-24 42 views
3

在我正在構建的應用程序中,當且僅當應用程序在後臺退出時,我需要檢測應用程序退出,因爲操作系統正在回收內存。檢測應用程序是否由於低RAM而被操作系統退出

從我自己的實驗中,在每個實例上調用onDestroy。我試過檢查isFinishing,但我並不是100%確定這種情況將其隔離。

@Override 
public void onDestroy() 
{ 
    super.onDestroy(); 
    Log.i("V LIFECYCLE", "onDestroy"); 
    if (!isFinishing()) 
    { 
     // are we here because the OS shut it down because of low memory? 
     ApplicationPreferences pref = new ApplicationPreferences(this); 
     // set persistant flag so we know next time that the user 
     // initiated the kill either by a direct kill or device restart. 
     pref.setThePersistantFlag(true); 
     Log.i("DEBUG", "onDestroy - ensuring that the next launch will result in a log out.."); 
    } 
} 

任何人都可以在這裏闡明我的問題嗎?謝謝。

回答

1

經過反覆試驗我。已經找到了一個完全適合任何感興趣的人的解決方案。在OS回收存儲器的情況下,應用程序狀態恢復時(onResume),我縮小了範圍。

public boolean wasJustCollectedByTheOS = false; 

@Override 
public void onSaveInstanceState(Bundle savedInstanceState) 
{ 
    super.onSaveInstanceState(savedInstanceState); 
    // this flag will only be present as long as the task isn't physically killed 
    // and/or the phone is not restarted. 
    savedInstanceState.putLong("semiPersistantFlag", 2L); 
} 

@Override 
public void onRestoreInstanceState(Bundle savedInstanceState) { 
    super.onRestoreInstanceState(savedInstanceState); 
    long semiPersistantFlag = savedInstanceState.getLong("semiPersistantFlag"); 
    if (semiPersistantFlag == 2L) 
    { 
     savedInstanceState.putLong("semiPersistantFlag", 0L); 
     this.wasJustCollectedByTheOS = true; 
    } 
} 

// this gets called immediately after onRestoreInstanceState 
@Override 
public void onResume() { 
    if (this.wasJustCollectedByTheOS){ 
     this.wasJustCollectedByTheOS = false; 
     // here is the case when the resume is after an OS memory collection  
    } 
} 
+0

它沒有爲我工作。我只是旋轉我的手機,上面的代碼告訴說,這是因爲操作系統內存收集。 – Ali 2017-07-16 17:39:17

0

我不知道它是否幫助你或沒有,

Android Activity類,當整個系統運行內存不足

public void onLowMemory() 

這就是所謂的,並想積極跑動過程試圖收緊腰帶。雖然沒有定義在此將被稱爲確切點,通常它會發生周圍的所有後臺進程已被殺害的時候,也就是達到殺死進程託管服務和前臺UI,我們想避免殺害點之前。

想要很好的應用程序可以實現此方法來釋放它們可能持有的任何緩存或其他不必要的資源。從此方法返回後,系統將爲您執行gc。

而且自:API級別14

public abstract void onTrimMemory (int level) 

當操作系統已經確定其是從它的過程中修剪不需要記憶的好時機的過程調用。例如,當它進入後臺並且沒有足夠的內存來保持儘可能多的後臺進程運行時,會發生這種情況。你不應該比較水平的精確值,因爲可以添加新的中間值 - 你通常要比較值是否大於或等於你有興趣在一個水平

+1

我試過了,除非應用程序在前臺,否則不會調用onLowMemory()。由於內存不足,我需要捕獲操作系統關閉設備的時間。 OnTrimMemory聽起來很有希望,但它只有4.0及以上版本,我們需要支持2.2及更高版本的設備。你可能會對isFinishing()和onDestroy()方法有所瞭解嗎?有沒有可以檢測操作系統關閉它的內存不足的組合?也許有一種方法來檢查操作系統是否在調用onDestroy時處於內存不足狀態? – 2012-07-25 04:27:52

+0

我轉述我的問題,使之更容易理解。 – 2012-07-25 04:47:11

+0

我解決了它。謝謝你的回答,但如果只有onTrimMemory(level)在老年人apis! – 2012-07-27 05:08:17

相關問題