Android - 在 OnCreate 中处理不会在屏幕旋转时调用的 http 调用的最佳方法是什么?

Android - What is best way of handling http call in OnCreate which doesn't get called on screen rotation?

我在学习android。遇到在 activity 的 oncreate 中加载数据的基本场景。因此,我试图在打开 activity 后立即加载数据,但是当我更改屏幕方向时,它会再次被调用。我了解 android 在屏幕方向期间恢复 activity 的状态。所以 oncreate 方法被调用。但我的问题是,一旦数据下载完毕,我不想一遍又一遍地进行 Http 调用。处理这个问题的最佳方法应该是什么?我想要不同的屏幕方向有不同的布局,但数据是相同的。我必须在 oncreate 中加载数据。

在配置更改时保留您的数据,例如通过 ViewModel. Your ViewModel would be responsible for performing the Web request (directly or via a repository) and delivering the results to the activity, such as via LiveData

如果您不想使用 Google arch 组件,可以选择 CommonsWare 答案的替代方法,您可以简单地检查 savedInstanceState 包是否为 null。如果是,那么如果第一次启动 activity 并且您可以加载数据。如果不是,那么它是重新创建的,您不应该加载数据。