检测应用程序是否由于低RAM而被操作系统退出

问题描述:

在我正在构建的应用程序中,当且仅当应用程序在后台退出时,我需要检测应用程序退出,因为操作系统正在回收内存。检测应用程序是否由于低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.."); 
    } 
} 

任何人都可以在这里阐明我的问题吗?谢谢。

经过反复试验我。已经找到了一个完全适合任何感兴趣的人的解决方案。在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

我不知道它是否帮助你或没有,

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