gpt4 book ai didi

android - 是从非 Activity 应用程序状态恢复的 Activity

转载 作者:行者123 更新时间:2023-11-29 23:33:07 26 4
gpt4 key购买 nike

我正在从网络加载数据并将其存储在 ViewModel 中.因此,当设备的方向发生变化时,数据会保留下来,我不必从网络上重新加载它。但是,如果应用程序进入非 Activity 状态(由于其他应用程序需要内存),ViewModel 中的数据将被删除,我将需要在恢复 Activity/fragment 时重新加载它。这个问题当然可以通过在 onSaveInstanceState() 方法中保存一些标志并在重新创建 Activity/fragment 。然而,这并没有区分从不活动中恢复和简单的方向改变。因此,每次我打开设备时,都会不必要地从服务器重新加载数据。

有没有办法知道 Activity/fragment 是否从非 Activity 状态恢复?

最佳答案

Is there a way to know if the activity/fragment was restored from an inactive state?

您可以利用以下事实:当您的应用进程被终止时,变量将返回到它们的默认(未初始化)值,并将其与正常的 savedInstanceState 逻辑相结合。

public class MainActivity extends AppCompatActivity {

private static boolean processWasAliveTheWholeTime;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

if (savedInstanceState == null) {
processWasAliveTheWholeTime = true;
} else {
if (!processWasAliveTheWholeTime) {
// if savedInstanceState is not null, that means we're being recreated.
// the only way processWasAliveTheWholeTime could be false is if our process was killed.
}
}
}
}

关于android - 是从非 Activity 应用程序状态恢复的 Activity ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52488914/

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