试图了解AsyncTask

时间:2013-08-09 17:20:47

标签: java android android-asynctask

我正在做一些修改,因为我是一个noob程序员 - 目前正在尝试理解AsyncTask。我有一个如何使用它来下载和显示网页内容的例子,但我很难理解哪些位做什么。不幸的是,我的笔记很垃圾。任何人都可以帮忙解释一下吗?

5 个答案:

答案 0 :(得分:1)

private class DownloadWebpageTask extends AsyncTask<String, Void, String> {

@Override
protected String doInBackground(String... urls) {
    String response = "";
    for (String url : urls) {
        DefaultHttpClient client = new DefaultHttpClient();
        HttpGet httpGet = new HttpGet(url);
        try {
            HttpResponse execute = client.execute(httpGet);
            InputStream content = execute.getEntity().getContent();

            BufferedReader buffer = new BufferedReader(
                    new InputStreamReader(content));
            String s = "";
            while ((s = buffer.readLine()) != null) {
                response += s;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    // since this is the background thread,  we need to return the string reponse so that onPostExecute can update the textview.
    return response
}

@Override
protected void onPostExecute(String result) {
    //  only onPostExecute,onProgressUpdate(Progress...), and onPreExecute can touch modify UI items since this is the UI thread.
    textView.setText(result);
}

答案 1 :(得分:0)

所以我真的不知道哪些部分是你最不清楚的,但让我解释基础:

您在代码中创建了一个私有的Async-Task。当您的应用程序继续正常运行时,此类的方法可以在后台运行(否则,它将冻结)。在doInBackground()方法中声明的所有内容都在后台执行。

要开始执行,请调用execute() - 方法,该方法当然不在您的私有Async-Task之外。在调用execute() - 方法之前,您实例化Async-Task。

onPostExecute()的方法可用于处理结果或返回值。当doInBackground()完成时调用此方法。

答案 2 :(得分:0)

您无法触及doInBackground内的视图,例如textView.setText(response);如果错误,你需要触摸onPreExecute和onPostExecute中的视图,并且在doInBackground中不要锁定UI线程,此外,onPre和onPost会锁定UI线程。

AsyncTask查看此链接,AsyncTask的文档。

答案 3 :(得分:0)

当您启动AsyncTask时,它会在不同的线程上执行doInBackground()方法,这样它就不会锁定您的UI或任何其他线程。当doInBackground()方法完成时,该方法的返回值将传递给onPostExecute()。 onPostExecute方法在UI线程上执行,因此您应该在这里对视图进行任何更改等。

答案 4 :(得分:0)

首先,暂且不说:几天前我终于“得到了”AsyncTask,所以我很高兴能帮助其他人现在也得到它。无论如何,我经历了一堆教程而没有真正理解它是如何工作的(官方文档 在这方面没有帮助)。这是最终让它点击的那个:http://www.brighthub.com/mobile/google-android/articles/82805.aspx