简体   繁体   English

旋转屏幕后如何防止我的 Asynctask 再次执行?

[英]How to prevent my Asynctask from executing again after rotating the screen?

For a college project I need to develop an Android app that retrieves JSON data from an API and displays it in a RecyclerView.对于大学项目,我需要开发一个 Android 应用程序,该应用程序从 API 检索 JSON 数据并将其显示在 RecyclerView 中。 One of the app requirements is that the Asynctask shouldn't be re-executed after changing screen orientation.应用要求之一是在更改屏幕方向后不应重新执行 Asynctask。 In other words, once the Asynctask is executed and the RecyclerView is displayed with the retrieved data, it shouldn't have to retrieve the data again after rotating the screen.换句话说,一旦执行了 Asynctask 并且 RecyclerView 与检索到的数据一起显示,它应该不必在旋转屏幕后再次检索数据。

For demonstration purposes I've added a toast in the onPostExecute method that shows the amount of items that have been displayed:出于演示目的,我在 onPostExecute 方法中添加了一个 toast 来显示已显示的项目数量:

在此处输入图片说明

在此处输入图片说明

As you can see, the toast reappears after rotating the screen, meaning the Asynctask was re-executed.如您所见,旋转屏幕后 toast 重新出现,这意味着重新执行了 Asynctask。 I want to prevent this from happening, but I can't figure out how.我想防止这种情况发生,但我不知道怎么做。

Try to add this line to your activity tag of the Manifest file.尝试将此行添加到清单文件的活动标记中。

<activity name= ".YourActivity" android:configChanges="orientation|screenSize"/>

When you write this parameter you don't want to handle anything in activity but Android will take care of this.当您编写此参数时,您不想处理活动中的任何内容,但 Android 会处理此问题。 It will remain the existing state of the activity.它将保持活动的现有状态。

If you are using different layout files for landscape orientation this method will break your layouts, so you can follow some alternative methods to keep the state.如果您为横向使用不同的布局文件,此方法将破坏您的布局,因此您可以使用一些替代方法来保持状态。

Override onSaveInstanceState method in your activity and add some param in the Bundle在您的活动中覆盖onSaveInstanceState方法并在Bundle添加一些参数

protected void onSaveInstanceState(Bundle bundle) {
  super.onSaveInstanceState(bundle);
  bundle.putLong("param", value);
}

And restore the value in onCreate to make sure the state was already created.并恢复onCreate的值以确保状态已经创建。

public void onCreate(Bundle bundle) {
  if (bundle != null){
    value = bundle.getLong("param");
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM