3

私が構築しているアプリケーションでは、OS がメモリを再利用しているため、バックグラウンドでアプリケーションが終了した場合にのみ、アプリケーションの終了を検出する必要があります。

私自身の実験から、 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..");
    }
}

ここで私の問題を明らかにできる人はいますか? ありがとうございました。

4

2 に答える 2

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    
    }
}
于 2012-07-27T04:56:24.330 に答える
0

お役に立てるかどうかわかりませんが、

Android Activityクラスから、

public void onLowMemory ()

これは、システム全体のメモリが不足しているときに呼び出され、積極的にプロセスを実行してベルトを締めようとする場合に呼び出されます。これが呼び出される正確なポイントは定義されていませんが、一般的には、すべてのバックグラウンド プロセスが強制終了されたとき、つまり、強制終了を回避したいサービスとフォアグラウンド UI をホストしているプロセスを強制終了するポイントに到達する前に発生します。

いいものにしたいアプリケーションは、このメソッドを実装して、保持している可能性のあるキャッシュやその他の不要なリソースを解放できます。このメソッドから戻った後、システムは gc を実行します。

以降: API レベル 14

public abstract void onTrimMemory (int level)

プロセスがそのプロセスから不要なメモリを削除するのに適した時期であるとオペレーティング システムが判断したときに呼び出されます。これは、たとえば、バックグラウンドで実行され、必要な数のバックグラウンド プロセスを実行し続けるのに十分なメモリがない場合に発生します。新しい中間値が追加される可能性があるため、レベルの正確な値と比較しないでください。通常、値が関心のあるレベル以上であるかどうかを比較します。

于 2012-07-24T06:10:46.493 に答える