Android AsyncTask用法

AsyncTask 是一个轻量级的线程,允许你直接将线程里完成的事情更新到UI线程中,类似于Thread + Handler的方式,只不过,它封闭起来完成了,如果你要完成一些费时复杂的工作,还是建议不要采用这个方法,取而代之的是使用Thread, ThreadPool等方式来完成。

AsyncTask 有4个步骤:onPreExecute, doInBackground, onProgressUpdate and onPostExecute,不过,它有3个可输入参数,这3个参数是可变参数,即个数可变,但类型一但确定,传过来的都必需是相同类型。

执行流程是:onPreExecute -> doInBackground -> onProgressUpdate -> onPostExecute

public class MyTask extends AsyncTask<Params, Progress, Result> {

	@Override
	protected Result doInBackground(Params... arg0) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	protected void onProgressUpdate(Progress... progress) {

	}

	@Override
	protected void onPostExecute(Result result) {

	}
	
}

三个参数与以上三个函数的输入参数一一对应,不过,通常onProgressUpdate的参数都由doInBackground传过来,在doInBackground中,可以调用publishProgress,这样在onProgressUpdate中,就能够按照你的想法,在UI线程中更新显示。

Android 官方文档手册中,给出对这三个参数的解释:

The three types used by an asynchronous task are the following:
    1. Params, the type of the parameters sent to the task upon execution.
    2. Progress, the type of the progress units published during the background computation.
    3. Result, the type of the result of the background computation.

这三个参数的类型,可以是Integer, Long, String, Void等,在使用过程中,参数都以数组形式存于可变参数变量中。

举例:

 private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> {
     protected Long doInBackground(URL... urls) {
         int count = urls.length;
         long totalSize = 0;
         for (int i = 0; i < count; i++) {
             totalSize += Downloader.downloadFile(urls[i]);
             publishProgress((int) ((i / (float) count) * 100));
             // Escape early if cancel() is called
             if (isCancelled()) break;
         }
         return totalSize;
     }

     protected void onProgressUpdate(Integer... progress) {
         setProgressPercent(progress[0]);
     }

     protected void onPostExecute(Long result) {
         showDialog("Downloaded " + result + " bytes");
     }
 }

这是一个下载是,显示进度条的例子,调用方法为:new DownloadFilesTask().execute(url1, url2, url3);

简单吧! ^-^! 大家一但用熟了,就对它爱不释手了,不过,千万记住,它只是个轻量级的线程!

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值