5

我一直在为几个项目使用这个 AsyncTask,但仍然不太明白它的<String, Void, String>含义。这些是否意味着未实现方法的参数类型?有什么命令吗(分别对应String、Void、String的方法是什么)?

4

3 回答 3

10

Android Docs AsyncTask页面:

android.os.AsyncTask<Params, Progress, Result>

异步任务使用的三种类型如下:

Params,执行时发送给任务的参数类型。

Progress,在后台计算期间发布的进度单元的类型。

Result,后台计算结果的类型。

现在我的理解很简单:

参数:(在您的情况下为字符串)是AsyncTask需要的参数。execute调用方法时必须传递它

进度:(在您的情况下为 Void)是进度的类型。无效意味着您没有使用它。如果是整数,您可以使用 10、20、30... 之类的值,并使用这些值在屏幕上显示进度条。

结果:(在您的情况下为字符串)是AsyncTask返回的结果。您正在返回一个字符串。你可以返回任何你想要的对象。

所以简单地说,它有点像一个方法,其中 Params 是参数,Result 是返回类型,progress 告诉你处理进度的状态。

如需进一步理解,请参阅本教程,同时引用同一页面的内容可能会有所帮助:

AsyncTask<TypeOfVarArgParams, ProgressValue, ResultValue>

TypeOfVarArgParams 作为输入传递给 doInBackground() 方法,ProgressValue 用于进度信息,ResultValue 必须从 doInBackground() 方法返回并作为参数传递给 onPostExecute()。

于 2012-11-26T12:54:55.900 回答
6

在文档中描述:

android.os.AsyncTask<Params, Progress, Result>

异步任务使用的三种类型如下:

Params, the type of the parameters sent to the task upon execution.
Progress, the type of the progress units published during the background computation.
Result, the type of the result of the background computation.

如果您不需要其中之一,请通过Void(但总是必须有 3 种类型)

于 2012-11-26T12:53:34.967 回答
2

AsyncTask中的第一个参数是指在doInBackground中要传递的参数,第二个参数是在onProgressUpdate中传递的,第三个参数是在onPostExecute中传递的。我们可以根据功能使用任何适合的数据类型。下面给出了参数类型(字符串、整数、字符串)的调用示例。

private class MyTask extends AsyncTask<String, Integer, String>
        {   
            protected String doInBackground(String... u)
            {
                // do something in background
                return null;    
            }
            protected void onPreExecute() 
            {               
                // do something before start
                    }
            public void onProgressUpdate(Integer... args)
            {    

            }                      
            protected void onPostExecute(String result) 
            {                                   
                              //  do something after execution  

            }
        }
于 2012-11-26T12:56:37.647 回答