原文: [置顶] Android菜鸟的成长笔记(13)——异步任务(Async Task)
Android的UI线程主要负责处理用户的事件及图形显示,因此主线程UI不能阻塞,否则会弹出一个ANR(Application Not Responding)异常,所以不能在UI线程中执行耗时操作。AsyncTask<>是一个抽象类,通常被继承,继承时需要指定三个泛型:
AsyncTask<Params, Progress, Result>
Params:启动任务执行的输入参数的类型
Progress:后台任务完成的进度值的类型
Result:后台执行任务完成后返回结果的类型
例子:从http://m.blog.csdn.net/blog/lxq_xsyu异步加载数据到手机上并显示(详细请看注释)
MainActivity.java
package com.example.testasyntask; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; import android.app.Activity; import android.app.ProgressDialog; import android.content.Context; import android.os.AsyncTask; import android.os.Bundle; import android.view.View; import android.webkit.WebView; import android.widget.TextView; public class MainActivity extends Activity { private TextView show; private WebView webView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); show = (TextView) findViewById(R.id.textView1); webView = (WebView) findViewById(R.id.webview); } public void download(View source) throws MalformedURLException{ DownTask task = new DownTask(this); task.execute(new URL("http://m.blog.csdn.net/blog/lxq_xsyu")); } class DownTask extends AsyncTask<URL, Integer, String>{ ProgressDialog pdialog; Context mContext; int hasRead = 0; public DownTask(Context ctx){ mContext = ctx; } /** * 该方法在执行后台耗时操作前被调用,初始化 */ @Override protected void onPreExecute() { pdialog = new ProgressDialog(mContext); pdialog.setTitle("任务正在执行中"); pdialog.setMessage("任务正在执行中,请耐心等待..."); pdialog.setCancelable(false); pdialog.setMax(182); pdialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); pdialog.setIndeterminate(false); pdialog.show(); } /** * 重写该方法就是后台线程将要完成的任务,该方法可以调用 * publishProgress(Progress.. values)方法更新任务的执行进度。 */ @Override protected String doInBackground(URL... params) { StringBuilder sb = new StringBuilder(); try { URLConnection conn = params[0].openConnection(); BufferedReader br = new BufferedReader( new InputStreamReader(conn.getInputStream(), "utf-8")); String line = null; while((line = br.readLine()) != null){ sb.append(line + "\n"); hasRead++; publishProgress(hasRead); } return sb.toString(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); return null; } } /** * 当doInBackground完成后,系统自动调用 */ @Override protected void onPostExecute(String result) { //show.setText(result); webView.loadDataWithBaseURL(null, result, "text/html", "utf-8", null); pdialog.dismiss(); } @Override protected void onProgressUpdate(Integer... values) { show.setText("已经读取了【" + values[0] + "】行!"); pdialog.setProgress(values[0]); } } }activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" android:gravity="center_horizontal"> <TextView android:id="@+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="102dp" android:text="TextView" /> <Button android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginBottom="31dp" android:text="开始下载" android:onClick="download"/> <WebView android:id="@+id/webview" android:layout_width="match_parent" android:layout_height="wrap_content"/> </LinearLayout>运行结果: