AsyncTask基本用法

/**
AsyncTask 可以判断的三种状态
AsyncTask.Status FINISHED Indicates that onPostExecute(Result) has finished.
AsyncTask.Status PENDING Indicates that the task has not been executed yet.
AsyncTask.Status RUNNING Indicates that the task is running.
*/
 
 
public class MyActivity extends Activity { 
	private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> {
 
 
	//在主线程中做准备工作
	protected void onPreExecute() {
        
        }
	
	//线程中运行
        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));//启动onProgressUpdate方法

                // 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");
        }
 
 
	//如果调用cancel方法后不会调用onPostExecute,直接调用onCancelled
	protected void onCancelled() {
           
        }
    }
	
	private AsyncTask<URL, Integer, Long> mLoginTask;

	protected void onCreate(Bundle savedInstanceState) {
		mLoginTask = (DownloadFilesTask) getLastNonConfigurationInstance();//读取先前保存的引用
    	
	
 
 
	if (mLoginTask != null && mLoginTask.isCancelled()) {
        //如果cancel成功就重新开始
            if (DEBUG) Log.d(TAG, "LoginTask previously cancelled, trying again.");
            mLoginTask = new LoginTask().execute();
        }
    }
 
 
 
 
 
 
	public Object onRetainNonConfigurationInstance() {
        	if (DEBUG) Log.d(TAG, "onRetainNonConfigurationInstance()");
        	if (mLoginTask != null) {
            	mLoginTask.cancel(true);//在线程运行中不能立即cancel,参数true表示线程应该被中断
        	}
        	return mLoginTask;
    	}
 
 
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Only鱼籽酱

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值