gpt4 book ai didi

Android - 如果 Activity 是第一次加载(不使用 SharedPreferences),则阻止 onResume() 函数

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:49:14 25 4
gpt4 key购买 nike

在我当前的应用程序中,当我第一次加载 Activity 时会触发 onResume 函数。我查看了 Activity Lifecycle ,但我没有找到防止这种情况发生的方法。

我可以在不使用 SharedPreferences 的情况下阻止第一次加载 Activity 时加载 onResume() 函数吗?

最佳答案

首先,正如 RvdK 所说,您不应该修改 Android Activity 生命周期,您可能必须重新设计 Activity 行为才能符合它。

无论如何,这是我看到的最好的方式:

1.在您的 Activity 中创建一个 bool 变量

public class MyActivity extends Activity{
boolean shouldExecuteOnResume;
// The rest of the code from here..
}

2.在你的onCreate中将它设置为false:

public void onCreate(){
shouldExecuteOnResume = false
}

3.然后在你的onResume中:

public void onResume(){
if(shouldExecuteOnResume){
// Your onResume Code Here
} else{
shouldExecuteOnResume = true;
}

}

通过这种方式,您的 onResume 将不会在第一次执行(shouldExecuteOnResume 为 false),但它将在加载 Activity 的所有其他时间执行(因为 shouldExecuteOnResume 将为真)。如果 Activity 随后被终止(由用户或系统),则在下次加载时将再次调用 onCreate 方法,因此 onResume 将不会执行,等等..

关于Android - 如果 Activity 是第一次加载(不使用 SharedPreferences),则阻止 onResume() 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15701163/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com