AsyncTask的基本用法

昨天复习了一下多线程和handler的用法,今天再来分享下AsyncTask的用法,虽然很基础,但是很重要。

AsyncTask的介绍,引用一下官网的英文doc:

AsyncTask enables proper and easy use of the UI thread. This class allows to perform background operations and publish results on the UI thread without having to manipulate threads and/or handlers.

AsyncTask is designed to be a helper class around Thread and Handler and does not constitute a generic threading framework. AsyncTasks should ideally be used for short operations (a few seconds at the most.) If you need to keep threads running for long periods of time, it is highly recommended you use the various APIs provided by thejava.util.concurrent package such as ExecutorThreadPoolExecutor and FutureTask.

An asynchronous task is defined by a computation that runs on a background thread and whose result is published on the UI thread. An asynchronous task is defined by 3 generic types, called ParamsProgress and Result, and 4 steps, called onPreExecutedoInBackgroundonProgressUpdate and onPostExecute.

一些注意事项:

1.AsyncTask必须在主线程创建。

2.execute()只能调用一次。

3.execute()必须在主线程执行。


ps:AsyncTask占用的内存大于使用handler


那么写一个小demo:

1.新建项目,编写xml布局:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <Button
        android:layout_margin="20dp"
        android:id="@+id/btn_start"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="开始下载"/>

	<ImageView 
	    android:id="@+id/img"
	    android:layout_width="match_parent"
	    android:layout_height="match_parent"
	    android:layout_margin="20dp"/>
</LinearLayout>

2.在MainActivity中定义事件,我直接写了一个继承AsyncTask的内部类:

package com.zero.asynctaskdemo;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;

/**
 * @author dh AsyncTask的简单使用 在后台下载一张图片,屏幕显示。
 */
public class MainActivity extends Activity {
	private Button btn;
	private ImageView img;
	public Bitmap bitmap;
	//URL的是本人存储在七牛云上的一张照片,你可以换
	private String url[] = {"http://carousel.qiniudn.com/01.jpg"};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		initView();
		btn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				//执行任务
				new DownlodImageTask().execute(url);		
			}
		});
	}

	private void initView() {
		btn = (Button) findViewById(R.id.btn_start);
		img = (ImageView) findViewById(R.id.img);
	}

	// 构造方法:第一个参数URL是doInBackground方法的参数,第三个Long是doInBackground方法的返回值
	// 第二的参数Integer用来设置进度,与onProgressUpdate方法对应
	private class DownlodImageTask extends AsyncTask<String, Integer, Long> {

		// 必须重写的方法,在后台执行耗时任务
		@Override
		protected Long doInBackground(String... params) {
			try {
					URL url = new URL(params[0]);
					HttpURLConnection conn = (HttpURLConnection) url
							.openConnection();
					conn.setDoInput(true);
					conn.connect();
					InputStream is = conn.getInputStream();
					bitmap = BitmapFactory.decodeStream(is);					
			} catch (MalformedURLException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
			return null;
		}

		// 修改UI
		@Override
		protected void onPostExecute(Long result) {
			img.setImageBitmap(bitmap);
			super.onPostExecute(result);
		}
	}

}

运行效果:






  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值