简介Android 中的AsyncTask

2019-12-10 18:52:26于海丽

•onPreExecute() 这里是最终用户调用Excute时的接口,当任务执行之前开始调用此方法,可以在这里显示进度对话框。

•onCancelled() 用户调用取消时,要做的操作

使用AsyncTask类,以下是几条必须遵守的准则:

•Task的实例必须在UI thread中创建;

•execute方法必须在UI thread中调用;

•不要手动的调用onPreExecute(), onPostExecute(Result),doInBackground(Params...), onProgressUpdate(Progress...)这几个方法;

•该task只能被执行一次,否则多次调用时将会出现异常;

一个超简单的理解 AsyncTask 的例子:

main.xml

<?xml version="." encoding="utf-"?> 
<LinearLayout xmlns:android="http://www.easck.com/apk/res/android" 
android:orientation="vertical" 
android:layout_width="fill_parent" 
android:layout_height="fill_parent" 
> 
<TextView 
android:id="@+id/textView" 
android:layout_width="fill_parent" 
android:layout_height="wrap_content" 
/> 
<ProgressBar 
android:id="@+id/progressBar" 
android:layout_width="fill_parent" 
android:layout_height="wrap_content" 
style="?android:attr/progressBarStyleHorizontal" 
/> 
<Button 
android:id="@+id/button" 
android:layout_width="fill_parent" 
android:layout_height="wrap_content" 
android:text="更新progressbar" 
/> 
</LinearLayout>