我在哪里可以写我AsyncTasks [英] Where can I write my AsyncTasks
问题描述
我创建一个应用程序,它大量使用了的AsyncTask
的从数据库中检索数据。我的问题是我有近12种不同的 AsyncTasks
键,它使我的code越来越脏,加上某些任务,不同活动之间共享的事实。
I'm creating an application which makes extensive use of AsyncTask
to retrieve data from a database. My problem is I've got nearly 12 different AsyncTasks
and it's making my code dirtier and dirtier, plus the fact that some tasks are shared among different activities.
一些的AsyncTask
我已经写有自己的Java类文件,但它不是一个总是理想的,因为一些请求需要访问应用程序的资源(庄家采用 Resources.getSystem()的getString(的StringID)
不可能的,或者需要通过我需要修改的参数作为参考的实例)
Some of the AsyncTask
I've already written have their own java class file, but it's not an always ideal since some requests need to access application's resources (making the use of Resources.getSystem().getString(stringId)
impossible, or requiring to pass instances I need to modify as parameters as reference)
有没有写的AsyncTask
类的任何推荐的方式?
Is there any recommended way to write AsyncTask
classes ?
推荐答案
它很难不知道确切的情况说,但如果你有一些做类似的任务,那么您可以在自己的文件创建,并创建可充分构造函数参数需要。
Its hard to say without knowing the exact circumstances but if you have some that do similar tasks then you can create them in their own file and create constructors that take the parameters you need.
您可以将其设置为接受上下文
,活动
对象,等等。然后让他们可重复使用。如果你有一些只对某一活动必要
然后我会让一个内部类,但如果它是由多个活动
然后我会让它独立的类,并使用构造函数(县)采取必要的参数。
You can set them up to accept a Context
, Activity
object, etc...then make them reusable. If you have some that are only necessary for a certain Activity
then I would make it an inner class but if it is used by multiple Activities
then I would make it a separate class and use constructor(s) to take the needed parameters.
我有许多 AsyncTasks
在我的应用程序,它只是取决于你如何需要他们。就像我说的,你可以传递一个上下文
来构造,当你需要它需要一个上下文
的对象。只是通过它像
I have many AsyncTasks
in my applications and it just depends on how you need them. As I said, you can pass a Context
to the constructor when you need it for objects that require a Context
. Just pass it like
MyTask task = new MyTask(this); // for passing Context or any other params the constructor takes
task.execute();
和任务
public class MyTask extends AsyncTask<...> // add AsyncTask params
{
Context context;
public MyTask(Context c)
{
context = c;
}
// methods
}
这篇关于我在哪里可以写我AsyncTasks的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!