关于AsyncTask的注意事项。

 

一个异步任务的执行一般包括以下几个步骤:

1.execute(Params... params),执行一个异步任务,需要我们在代码中调用此方法,触发异步任务的执行。

2.onPreExecute(),在execute(Params... params)被调用后立即执行,一般用来在执行后台任务前对UI做一些标记。

3.doInBackground(Params... params),在onPreExecute()完成后立即执行,用于执行较为费时的操作,此方法将接收输入参数和返回计算结果。在执行过程中可以调用publishProgress(Progress... values)来更新进度信息。

4.onProgressUpdate(Progress... values),在调用publishProgress(Progress... values)时,此方法被执行,直接将进度信息更新到UI组件上。

5.onPostExecute(Result result),当后台操作结束时,此方法将会被调用,计算结果将做为参数传递到此方法中,直接将结果显示到UI组件上。

 

注意事项:

doInBackground中需要一个条件来操作Thread.sleep(int).否则只会执行一次。

AsyncTask适合处理短时间的操作,长时间的操作,比如下载一个很大的视频,这就需要你使用自己的线程来下载。

package com.example.mediaplayerproject;

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.TextView;

public class AsyTest extends Activity {

	private TextView show = null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.setContentView(R.layout.asy);
		show = (TextView) findViewById(R.id.show);
		new asyImpl().execute(1000);
	}

	private class asyImpl extends AsyncTask<Integer, Integer, String> {

		@Override
		protected void onPostExecute(String result) {
			super.onPostExecute(result);
		}

		@Override
		protected void onProgressUpdate(Integer... values) {
			AsyTest.this.show.setText("更新的数据:  " + Math.random() * 100);
		}

		@Override
		protected String doInBackground(Integer... params) {
			try {
				while (true) {
					Thread.sleep(params[0]);
					this.publishProgress(100);
				}

			} catch (Exception e) {
			}
			return null;
		}

	}
}

  

---恢复内容结束---

posted @ 2013-05-24 17:56  懵懵懂懂的it人生  阅读(173)  评论(0编辑  收藏  举报