AsyncTask--异步任务学习

为什么使用AsyncTask?
android是单线程模型,只有主线程可以操作UI,虽然一定程度上保证ui的稳定性和准确性,但是也不能将任务全部放到主线程中去,不然容易出现ANR
一般都是把耗时操作放在异步线程中执行
而android官方给我们提供了一个抽象类,就是AsyncTask类,专门用来 封装、简化异步操作
下面是AsyncTask的一些简介
AsyncTask<Params,Progress,Result>是一个抽象类,通常用于被继承, 继承AsyncTask需要指定三个泛型参数
Params:启动任务时输入参数的类型
Progress:后台任务执行中返回进度值的类型
Result:后台执行任务完成后返回结果的类型

构建AsyncTask子类的回调方法
doInBackground:必须重写,异步执行后台线程将要完成的任务
onPreExecute:执行后台耗时操作前被调用,通常用户完成一些初始化操作
onPostExecute:当doInBackground()完成后,系统会自动调用该方法,并将 doInBackground方法返回的值传给该方法
onProgressUpdate:在doInBackground方法中调用publishProgress方法更新任务的执行进度后,就会触发该方法

下面是一个异步加载网络图片的小demo
首先是一个布局文件,里面有一个ImageView用来显示网络图片,还有一个进度条,用来提示用户正在加载
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
	android:padding="18dp"
    tools:context=".MainActivity" >

    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="#000111" />

    <ProgressBar
        android:id="@+id/progressBar1"
        style="?android:attr/progressBarStyleLarge"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignTop="@+id/imageView1"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="138dp"
        android:visibility="gone" />
	
</RelativeLayout>

异步加载图片的操作

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

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.widget.ImageView;
import android.widget.ProgressBar;

public class MainActivity extends Activity {
	ImageView iv;
	ProgressBar p;
	//网络图片的路径
	String URL = "https://ss0.bdstatic.com/94oJfD_bAAcT8t7mm9GUKT-xh_/timg?image&quality=100&size=b4000_4000&sec=1462451281&di=460266e0c088744e0640e52ffcb8bc27&src=http://a.hiphotos.baidu.com/image/pic/item/f9dcd100baa1cd11daf25f19bc12c8fcc3ce2d46.jpg";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		iv = (ImageView) findViewById(R.id.imageView1);
		p = (ProgressBar) findViewById(R.id.progressBar1);
		new MyAsyncTask().execute(URL);//调用异步任务加载图片
	}


	//因为我们要传递一个网络图片的URL,所以AsyncTask的第一个泛型参数是String
	//而我们要得到的结果是一张图片,所以第三个泛型参数用Bitmap
	class MyAsyncTask extends AsyncTask<String, Void, Bitmap> {

		//执行异步加载图片的操作 
		protected Bitmap doInBackground(String... params) {
			// TODO Auto-generated method stub
			String url = params[0];//启动异步任务输入的参数,可以有多个,这里只有网络图片的URL
			Bitmap bitmap = null;
			URLConnection con;
			InputStream is;
			try {
				con = new URL(url).openConnection();
				is = con.getInputStream();
				BufferedInputStream bis = new BufferedInputStream(is);
				Thread.sleep(2000);//这里让线程停两秒,体现出图片加载的效果
				bitmap = BitmapFactory.decodeStream(bis);
				is.close();
				bis.close();
			} catch (MalformedURLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return bitmap;
		}
		//图片加载完毕之后,显示图片,并且隐藏进度条
		protected void onPostExecute(Bitmap bitmap) {
			// TODO Auto-generated method stub
			super.onPostExecute(bitmap);
			p.setVisibility(View.GONE);
			iv.setImageBitmap(bitmap);
		}
		//在加载前 显示进度条 提示用户正在加载图片
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
			p.setVisibility(View.VISIBLE);
		}

	}

}
 最后别忘了加网络权限 
 
<uses-permission android:name="android.permission.INTERNET"/>
以上内容参考自慕课网Android必学-AsyncTask
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值