检测是否申请由操作系统,因为低内存退出 [英] Detect whether application is quit by the OS because of low RAM

查看:122
本文介绍了检测是否申请由操作系统,因为低内存退出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我建立的应用程序,我需要检测应用程序退出,当且仅当应用程序已经退出时,其背景是因为操作系统回收内存。

In the application I'm building, I need to detect the application quitting if and only if the application has been quit when its in the background because the OS is reclaiming memory.

从我自己的实验中,的onDestroy被称为上的每一个实例。我试过检查isFinishing但我不是100%肯定这情况下,这它隔离到。

From my own experimentation, the onDestroy is called on EVERY instance. I've tried checking for isFinishing but I'm not 100% sure which situations this isolates it to.

@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..");
    }
}

任何人都可以阐明我的问题吗?三江源。

Can anyone shed light on my issue here? Thankyou.

推荐答案

经过反复试验,我已经制定了人那有兴趣的作品完美的解决方案。当应用程序状态被恢复(onResume)在OS回收内存的情况下,我已经收窄的情况。

Through trial and error I have worked out a solution that works perfectly for anyone thats interested. I have narrowed down the case when the application state is being resumed (onResume) in the case of the OS reclaiming memory.

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

这篇关于检测是否申请由操作系统,因为低内存退出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆