本文介绍了我应该在 MainActivity 扩展 Activity 中使用 AsyncTask 类吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道 AsyncTask 是否在运行线程的主活动 (MainActivity.java) 中使用.

I was wondering if AsyncTask was made to be used inside the main activity (MainActivity.java) running the thread.

例如我注意到很多教程在使用 AsyncTask 时,他们在主类中声明了一个私有类,扩展了 Activity 而不是创建一个独立的 .javaAsyncTask (MyAsyncTask.java) class.

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() 因为它属于 Activity 类,那么我将如何能够在扩展 AsyncTask 而不是 Activity 的独立 AsyncTask (MyAsyncTask.java) 中使用此方法.

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.

推荐答案

那完全没问题.我经常这样做,但这取决于您如何使用它.如果它可以被其他 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 例如 context 或其他变量.

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 文件中创建一个构造函数,并让它接受 context 作为参数以及您需要的任何其他内容.然后你可以更新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();

这篇关于我应该在 MainActivity 扩展 Activity 中使用 AsyncTask 类吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 07:25