安卓多線程編程系列2:異步任務的使用之使用異步任務帶有進度的橫向滾動條下載網絡圖片

異步任務是多線程編程中經常使用的一種方式,這裏我們介紹一下使用異步任務帶有進度的下載網絡圖片的使用方法。

整體思路:在xml文件中放置一個Button控件和一個ImageView控件,定義一個繼承AsyncTask類的MyTask類,在這個類中重寫onPreExecute、onProgressUpdate、doInBackground、onPostExecute這四個方法,分別用於表示任務執行之前的操作、進度更新操作、完成耗時操作、更新UI操作,在onPreExecute這個方法中,展示定義的dialog對象,在onProgressUpdate方法中設置進度條的值,在doInBackground方法中獲取網絡圖片並返回一個bitmap格式的圖片對象,在onPostExecute方法中將獲取的圖片綁定到ImageView上,並使dialog對象消失。

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="Button" />

    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:src="@drawable/ic_launcher" />
   
</RelativeLayout>
MainActivity.java文件:

package com.example.android_asynctask_download2;
//使用異步任務橫向滾動條帶有進度的下載圖片
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

import org.apache.http.HttpResponse;
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.ByteArrayBuffer;

import android.R.integer;
import android.os.AsyncTask;
import android.os.Bundle;
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.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageButton;
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);
		dialog=new ProgressDialog(this);
		dialog.setTitle("提示");
		dialog.setMessage("正在下載,請稍候...");
//		設置進度條的樣式爲橫向的
		dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
//		設置不允許進度條對話框失去焦點
		dialog.setCancelable(false);
		button=(Button)findViewById(R.id.button1);
		imageView=(ImageView)findViewById(R.id.imageView1);
		button.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				new MyTask().execute(image_path);
			}
		});
		
	}
	
	public class MyTask extends AsyncTask<String, Integer, Bitmap>{

		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
			dialog.show();
		}
		
		@Override
		protected void onProgressUpdate(Integer... values) {
			// TODO Auto-generated method stub
			super.onProgressUpdate(values);
			dialog.setProgress(values[0]);//進度條更新
		}
		
		@Override
		protected Bitmap doInBackground(String... params) {
			// TODO Auto-generated method stub
			Bitmap bitmap=null;
			ByteArrayOutputStream outputStream=new ByteArrayOutputStream();
			InputStream inputStream=null;
			try {
				HttpClient httpClient=new DefaultHttpClient();
				HttpGet httpGet=new HttpGet(params[0]);//取第0個參數
				HttpResponse httpResponse=httpClient.execute(httpGet);
				if(httpResponse.getStatusLine().getStatusCode()==200){
					inputStream=httpResponse.getEntity().getContent();
//					先要獲得文件的總長度
					long file_length=httpResponse.getEntity().getContentLength();
					int len=0;
					byte[] data=new byte[1024];
					int total_length=0;
//					int value=0;//聲明一個刻度
					while ((len=inputStream.read(data))!=-1) {
						total_length+=len;
						int value=(int)((total_length/(float)file_length)*100);
						publishProgress(value);//發佈刻度
						outputStream.write(data,0,len);
					}
					byte[] result=outputStream.toByteArray();
					bitmap=BitmapFactory.decodeByteArray(result, 0, result.length);
				}
			} catch (Exception e) {
				// TODO: handle exception
				e.printStackTrace();
			}finally{
				if(inputStream!=null){
					try {
						inputStream.close();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}
			return bitmap;
		}
		
		@Override
		protected void onPostExecute(Bitmap result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			dialog.dismiss();
			imageView.setImageBitmap(result);
		}
		
	}

	@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;
	}

}



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