安卓多线程编程系列1:异步任务的使用之使用异步任务圆圈滚动条下载网络图片

线程在安卓开发中非常重要,很大程度上决定安卓app的性能。不会阻碍主线程的操作,并且会把结果发布在主线程上。在android3.0版本以上,不允许主线程直接访问网络,为了让UI在展示的过程中比较流畅。需要开启新的子线程去完成下载等耗时任务的操作,并把下载结果更新到UI上。AsyncTask(异步任务)是一个线程框架,封装了Thread和Handler,异步任务用于短时间的耗时操作,如果是长时间的耗时操作的话要用线程池。

整体思路:在xml文件中放入一个Button控件和一个ImageView控件,在activity中 声明一个异步任务,使用异步任务的规则:1.声明一个类继承AsyncTask 标注三个参数的类型,2.第一个参数表示要执行的任务通常是网络的路径,第二个参数表示进度的刻度,第三个参数表示任务执行的返回结果类型,重写三个方法onPreExecute、doInBackground、onPostExecute,这三个方法分别表示任务执行之前的操作、完成耗时操作、更新UI操作,在onPreExecute方法中展示定义的dialog对象,在doInBackground方法中,通过一个网址来获取网络图片,并返回一个bitmap类型的图片对象,在onPostExecute这个方法中,将获取的图片绑定到ImageView控件上,并将dialog对象消失。在activity的onCreate方法中执行异步任务操作,并传递一个获取图片的网址。注意在清单文件AndroidManifest.xml中添加连接网络的授权。

activity_main.xml文件:

<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:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:text="下载网络图片" />

    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="150dp"
        android:src="@drawable/ic_launcher" />

</RelativeLayout>
MainActivity.java文件:

package com.example.android_asynctask_download;
//使用异步任务圆形滚动条下载图片并显示
import java.io.IOException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.DefaultClientConnection;
import org.apache.http.util.EntityUtils;

import android.os.AsyncTask;
import android.os.Bundle;
import android.renderscript.Program;
import android.app.Activity;
import android.app.ProgressDialog;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

public class MainActivity extends Activity {

	private Button button;
	private ImageView imageView;
	private String image_path="http://pica.nipic.com/2007-11-09/200711912453162_2.jpg";
	private ProgressDialog dialog;
	
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        button=(Button)findViewById(R.id.button1);
        imageView=(ImageView)findViewById(R.id.imageView1);
        dialog=new ProgressDialog(this);
        dialog.setTitle("提示信息");
        dialog.setMessage("正在下载,请稍候...");
        button.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
//              执行异步任务的操作
				new MyTask().execute(image_path);
/*
//				new Thread(new Runnable() {
//					
//					@Override
//					public void run() {
//						// TODO Auto-generated method stub

//				在UI的主线程中,不能直接访问网络
						HttpClient httpClient=new DefaultHttpClient();
						HttpGet httpGet=new HttpGet(image_path);
						try {
							httpClient.execute(httpGet);
							
						} catch (ClientProtocolException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						} catch (IOException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
//					 }
//				  }).start();
						*/
					
				
			}
		});
    }
 
//  声明一个异步任务    void表示是没有类型的
//  使用异步任务的规则:
//    1.声明一个类继承AsyncTask 标注三个参数的类型
//    2.第一个参数表示要执行的任务通常是网络的路径,第二个参数表示进度的刻度
//    第三个参数表示任务执行的返回结果类型
    
    public class MyTask extends AsyncTask<String, Void, Bitmap>{
    	
//     表示任务执行之前的操作
    	@Override
    	protected void onPreExecute() {
    		// TODO Auto-generated method stub
    		super.onPreExecute();
    		dialog.show();
    	}
    	
//     主要是完成耗时操作
	    @Override
	    protected Bitmap doInBackground(String... params) {
		    // TODO Auto-generated method stub
//	    	使用网络链接类HttpClient类完成对网络数据的提取
	    	HttpClient httpClient=new DefaultHttpClient();
	    	HttpGet httpGet=new HttpGet(params[0]);
	    	Bitmap bitmap=null;
	    	try {
				HttpResponse httpResponse=httpClient.execute(httpGet);
				if(httpResponse.getStatusLine().getStatusCode()==200){
					HttpEntity httpEntity=httpResponse.getEntity();
//					把一个实体类转化成一个字节数组
					byte[] data=EntityUtils.toByteArray(httpEntity);
					bitmap=BitmapFactory.decodeByteArray(data, 0, data.length);
					
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		    return bitmap;
	    }
	    
//	        主要是更新UI操作
	    @Override
	    protected void onPostExecute(Bitmap result) {
	        // TODO Auto-generated method stub
	        super.onPostExecute(result);
	        imageView.setImageBitmap(result);
	        dialog.dismiss();
	    }
    	
    }
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
    
}



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章