简体   繁体   English

片段或父活动中的Asynctask?

[英]Asynctask in Fragment or Parent Activity?

I have a scenario and I an not sure on what path to go. 我有一个场景,我不知道要走哪条路。

Scenario 脚本

The app has a Home activity which displays various fragments. 该应用程序有一个Home活动,显示各种片段。 The data in the fragments can come either from the web or a local database and is retrieved using an asynctask. 片段中的数据可以来自Web或本地数据库,并使用asynctask进行检索。

From what I saw, I have 2 alternatives: 从我看到的,我有两个选择:

  1. Put the Asynctask in parent activity and then use fragment.newInstance(parameters) to pass the result to the fragment. 将Asynctask放入父活动中,然后使用fragment.newInstance(parameters)将结果传递给片段。 However, if in my asynctask I need to update the progress or some info on the fragment, each time I will have to call newInstance with the new set of parameters. 但是,如果在我的asynctask中我需要更新片段的进度或一些信息,每次我都必须使用新的参数集调用newInstance。

  2. Add the fragment and put the asynctask in it, in this way when progress is needed, I can update the fragment's views, as I have access to them + when the asynctask is done, I can populate the list with the info. 添加片段并将asynctask放入其中,这样当需要进度时,我可以更新片段的视图,因为我可以访问它们+当asynctask完成时,我可以用信息填充列表。

What would be the correct approach ? 什么是正确的方法?

LE: actually for point 1 in order to update the fragment I can call fragment's public methods after I find it with findFragmentById in the parent activity LE:实际上对于第1点来更新片段我在父活动中使用findFragmentById找到它后可以调用片段的公共方法

A better way if you have multiple tasks would be to use an IntentService : http://mobile.tutsplus.com/tutorials/android/android-fundamentals-intentservice-basics/ 如果您有多个任务,更好的方法是使用IntentService: http//mobile.tutsplus.com/tutorials/android/android-fundamentals-intentservice-basics/

You would have a better control to what you're requesting and what you want to cancel. 您可以更好地控制要求的内容以及要取消的内容。

I would go with the second approach. 我会采用第二种方法。
My primary reason though would be to avoid the issues that can happen on screen orientation change while the AsyncTask is working. 我的主要原因是避免在AsyncTask工作时屏幕方向改变可能发生的问题。

I would go with method 2, but take it a step further. 我会采用方法2,但更进一步。

Have a separate fragment to run your async task. 有一个单独的片段来运行您的异步任务。 This way, you can handle any configuration changes (not just rotating screen) without any issues. 这样,您可以处理任何配置更改(不仅仅是旋转屏幕)而不会出现任何问题。

In another fragment, you can display the data. 在另一个片段中,您可以显示数据。 You can pass the data from your async task fragment via callbacks to the activity, and have the activity call a method in the display fragment to update the data. 您可以通过回调将数据从异步任务片段传递到活动,并让活动调用显示片段中的方法来更新数据。

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

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