我应该使用的AsyncTask类扩展活动的MainActivity里面? [英] Should I use AsyncTask class inside the MainActivity extending Activity?
问题描述
我在想,如果的AsyncTask
调整为主要活动内使用(MainActivity.java <$ C C $>)运行线。
I was wondering if AsyncTask
was made to be used inside the main activity (MainActivity.java
) running the thread.
例如,我发现很多教程时使用的AsyncTask
他们宣布延长活动的主类中的私有类
而不是创建一个独立的的.java
文件的的AsyncTask
( MyAsyncTask.java
)类
。
For example I noticed many tutorials when using the AsyncTask
they declare a private class inside the main class extending the Activity
rather than creating an independent .java
file for that AsyncTask
(MyAsyncTask.java
) class
.
不过,我注意到,使用一个独立的文件,当我不能够运行 runOnUIThread
(),因为它属于活动
类,所以我怎么样才能用这种方法里面那个独立的的AsyncTask
(MyAsyncTask.java),它扩展了的AsyncTask
,而不是活动
。
But I noticed that when using an independent file i'm not being able to run the runOnUIThread
() because it belongs to the Activity
class, so how will i be able to use this method inside that independent AsyncTask
(MyAsyncTask.java) which extends AsyncTask
and not Activity
.
推荐答案
这是完全没问题。我经常这样做,但是这取决于你如何使用它。如果它可以由诺特活动
然后我给它自己的类或共享类。但是,如果它是一个单一的目的,那么我会让它的内部类的 MainActivity
。
That is completely fine. I do it often but it depends on how you are using it. If it may be used by othe Activities
then I give it it's own class or a shared class. But if it is for a single purpose then I would make it an inner class of the MainActivity
.
使它的内部类的好处是,它可以直接访问的类成员变量。如果你让一个单独的类,那么你只需要创建一个构造函数,如果你需要传递 PARAMS
如上下文
或其它变量。
The benefit of making it an inner class is that it has direct access to that classes member variables. If you make it a separate class then you just need to create a constructor for it if you need to pass in params
such as a context
or other variables.
我不知道你在做什么,但我不知道你需要 runOnUiThread()
。您可以创建在的AsyncTask
文件中的构造函数,并让它接受上下文
,因为你需要一个参数和其他任何。然后,您可以更新 UI
在 onPostExecute()
I don't know exactly what you are doing but I'm not sure you need runOnUiThread()
. You can create a constructor in your AsyncTask
file and have it accept context
as a param and whatever else you need. Then you can update the UI
in onPostExecute()
示例
Public class MyAsyncTask extends AsyncTask
{
private Context context;
public MyAsyncTask(Context context) { // can take other params if needed
this.context = context;
}
// Add your AsyncTask methods and logic
//you can use your context variable in onPostExecute() to manipulate activity UI
}`
然后把它在你的 MainActivity
MyAsyncTask myTask = new MyAsyncTask(this); //can pass other variables as needed
myTask.execute();
这篇关于我应该使用的AsyncTask类扩展活动的MainActivity里面?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!