Android中AsyncTask异步任务使用详细实例(二)

MainActivity如下:

package cn.cc;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import cn.cc.AsyncTaskSubClass.AsyncTaskCallbackInterface;
import cn.cc.AsyncTaskSubClass.AsyncTaskPerformInterface;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.widget.ImageView;
/**
 * Demo描述:
 * 平常我们写一个AsyncTask的时候把异步操作已经异步完成后的操作
 * 是放在doInBackground()和onPostExecute()方法中的.
 * 这样显得代码比较臃肿,而且不方便复用.
 * 所以在此采用AsyncTask与回调结合的方式:抽象AsyncTask的代码从而
 * 简化代码,并且利于重用.
 */
public class MainActivity extends Activity {
	private Context mContext;
	private ImageView mImageView;
	private AsyncTaskSubClass mAsyncTaskSubClass;
	private String mFavIconPathString =null;
	private final String FAVICON_SERVICE="http://www.google.com/s2/favicons?domain=";
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        init();
    }
    
    private void init(){
    	mContext=this;
    	mImageView=(ImageView) findViewById(R.id.imageView);
    	mFavIconPathString = FAVICON_SERVICE+"http://www.ifeng.com/";
        startAsyncTask();
    }
    
	private void startAsyncTask() {
		mAsyncTaskSubClass = new AsyncTaskSubClass(mContext,
				new AsyncTaskPerformInterface() {
					@Override
					public Bitmap performAsyncTask(String string) {
						try {
							Bitmap bitmap=null;
							InputStream inputStream = null;
							URL imageUrl = new URL(string);
							HttpURLConnection httpURLConnection = (HttpURLConnection) imageUrl.openConnection();
							httpURLConnection.setConnectTimeout(5000);
							httpURLConnection.setRequestMethod("GET");
							if (httpURLConnection.getResponseCode() == 200) {
								inputStream = httpURLConnection.getInputStream();
								bitmap = BitmapFactory.decodeStream(inputStream);
								return bitmap;
							}

						} catch (Exception e) {
							
						}
						return null;
					}
				}, 
				new AsyncTaskCallbackInterface() {
					@Override
					public void asyncTaskFinishCallback(Bitmap bitmap) {
						mImageView.setImageBitmap(bitmap);
					}
				});
		//开始执行一个异步任务
		mAsyncTaskSubClass.execute(mFavIconPathString);
	}
}


AsyncTaskSubClass如下:

package cn.cc;
import android.content.Context;
import android.graphics.Bitmap;
import android.os.AsyncTask;
//构造函数AsyncTask<Params, Progress, Result>参数说明: 
//Params   启动任务执行的输入参数
//Progress 后台任务执行的进度
//Result   后台计算结果的类型
public class AsyncTaskSubClass extends AsyncTask<String, Integer, Bitmap> {
	private Context mContext;
	private AsyncTaskPerformInterface mAsyncTaskPerformInterface;
	private AsyncTaskCallbackInterface mAsyncTaskCallbackInterface;
	
	public AsyncTaskSubClass(
			     Context context,
			     AsyncTaskPerformInterface asyncTaskPerformInterface,
			     AsyncTaskCallbackInterface asyncTaskCallbackInterface) {
		super();
		this.mContext = context;
		this.mAsyncTaskPerformInterface = asyncTaskPerformInterface;
		this.mAsyncTaskCallbackInterface = asyncTaskCallbackInterface;
	}

	//执行异步操作的回调接口
	public interface AsyncTaskPerformInterface {
		public Bitmap performAsyncTask(String string);
	}
	
	//异步操作完成的回调接口
	public interface AsyncTaskCallbackInterface {
		public void asyncTaskFinishCallback(Bitmap bitmap);
	}
	
	@Override
	protected void onPreExecute() {
		super.onPreExecute();
		System.out.println("调用onPreExecute()方法--->准备开始执行异步任务");  
	}
	
	//此处strings[0]对应于AsyncTask<String, Integer, Bitmap>
	//中的第一个参数,即异步任务的输入参数.
	//此处Bitmap对应于AsyncTask<String, Integer, Bitmap>
	//中的第三个参数,即异步任务的输出结果.
	@Override
	protected Bitmap doInBackground(String... strings) {
		System.out.println("调用doInBackground()方法--->开始执行异步任务");
		Bitmap bitmap=null;
		if(mAsyncTaskPerformInterface!=null){
			bitmap=mAsyncTaskPerformInterface.performAsyncTask(strings[0]);
		}
		return bitmap;
	}
	
	//此处Bitmap对应于AsyncTask<String, Integer, Bitmap>
	//中的第三个参数,即异步任务的输出结果.
	@Override
	protected void onPostExecute(Bitmap bitmap) {
		System.out.println("调用onPostExecute()方法--->异步任务执行完毕");
		if(mAsyncTaskCallbackInterface!=null){
			mAsyncTaskCallbackInterface.asyncTaskFinishCallback(bitmap);
		}
	}

	//异步执行时在主线程中更新异步任务的执行信息
	//此处values[0]对应于AsyncTask<String, Integer, Bitmap>
	//中的第二个参数,即异步任务的执行进度.
	@Override
	protected void onProgressUpdate(Integer... values) {
		return;
	}
	
	//异步任务被取消时,在主线程中执行相关的操作 
	@Override
	protected void onCancelled() {
		super.onCancelled();
		System.out.println("调用onCancelled()方法--->异步任务被取消");
	}

}

main.xml如下:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="#ffffff">

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true" />

</RelativeLayout>




郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。