正确的方法来了解活动是否已被销毁

Che*_*eng 9 android

我可以知道知道某项活动是否已被销毁的正确方法是什么?目前,我使用以下方式.

private volatile boolean isOnDestroyCalled = false;

@Override
protected void onDestroy() {
    super.onDestroy();
    isOnDestroyCalled = true;
}

public boolean isOnDestroyCalled() {
    return this.isOnDestroyCalled;
}
Run Code Online (Sandbox Code Playgroud)

有没有比上面更好的方法?

Car*_*nal 4

这会起作用,但有时,如果您的应用程序在其他应用程序需要优先级时处于非活动状态一段时间,操作系统会关闭您的应用程序。当然,我知道当这种情况发生时,变量将被取消,但不确定在你的情况下是否会使用进入主内存的 易失性。但确保获得正确值的一种方法是将其保存在 SharedPreferences 中。