Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> Android學習筆記之AsyncTask實現文件下載任務

Android學習筆記之AsyncTask實現文件下載任務

編輯:關於Android編程

(1)該文件下載主要演示異步任務下載圖片

(2)布局代碼如下:一個ImageView用於存放下載的圖片,Button用於開始異步任務下載



    

    

(3)控制類

package com.example.asynctask_download;

import java.io.IOException;

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.util.EntityUtils;

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

public class MainActivity extends Activity {

	private Button button1;
	private ImageView imageView1;
	private final String IMAGE_PATH = "http://www.baidu.com/img/bd_logo1.png";// 設置網頁圖片的地址
	private ProgressDialog progressDialog;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		button1 = (Button) this.findViewById(R.id.button1);
		imageView1 = (ImageView) this.findViewById(R.id.imageView1);
		/*
		 * 下載進度條的設置
		 */
		progressDialog = new ProgressDialog(this);
		progressDialog.setTitle("提示");
		progressDialog.setCancelable(false);
		progressDialog.setMessage("正在下載圖片,請耐心等候!");

		button1.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				/*
				 * 異步任務、執行下載圖片
				 */
				new MyTask().execute(IMAGE_PATH);
			}
		});
	}

	/*
	 * 異步任務:三個參數、四個步驟onPreExecute()、
	 * doInBackground()、onProgressUpdate()、onPostExecute()、沒有參數傳傳進去的時候可以使用void
	 */
	public class MyTask extends AsyncTask {

		/*
		 * onPreExecute()方法在後台操作開始前運行在UI線程上
		 */
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			progressDialog.show();
		}

		/*
		 * doInBackground方法運行在後台並處理後台操作
		 */
		@Override
		protected byte[] doInBackground(String... params) {
			HttpClient httpClient = new DefaultHttpClient();
			HttpGet httpGet = new HttpGet(params[0]);
			byte[] result = null;

			try {
				HttpResponse httpResponse = httpClient.execute(httpGet);
				if (httpResponse.getStatusLine().getStatusCode() == 200) {
					result = EntityUtils.toByteArray(httpResponse.getEntity());
				}
			} catch (ClientProtocolException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			} finally {
				httpClient.getConnectionManager().shutdown();
			}

			return result;
		}

		@Override
		protected void onProgressUpdate(Integer... values) {
			super.onProgressUpdate(values);
		}

		/*
		 * 一旦後台操作完畢,onPostExecute()方法就會在UI線程中運行
		 */
		@Override
		protected void onPostExecute(byte[] result) {
			super.onPostExecute(result);
			/*
			 * 將下載的bitmap放置在imagView中去
			 * result就是下載的圖片
			 */
			Bitmap bitmap = BitmapFactory.decodeByteArray(result, 0,
					result.length);
			imageView1.setImageBitmap(bitmap);
			progressDialog.dismiss();
		}

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

}

結果:

\

\


(5)顯示帶刻度條的文件下載:<喎?/kf/ware/vc/" target="_blank" class="keylink">vcD4KPHA+PC9wPgo8cHJlIGNsYXNzPQ=="brush:java;">package com.example.asynctask_download; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; 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.util.EntityUtils; import android.R.integer; import android.app.Activity; import android.app.ProgressDialog; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.AsyncTask; import android.os.Bundle; import android.view.Menu; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.ImageView; public class MainActivity extends Activity { private Button button1; private ImageView imageView1; private final String IMAGE_PATH = "http://img.daimg.com/uploads/allimg/150114/3-150114151438.jpg";// 設置網頁圖片的地址 private ProgressDialog progressDialog; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); button1 = (Button) this.findViewById(R.id.button1); imageView1 = (ImageView) this.findViewById(R.id.imageView1); /* * 下載進度條的設置 */ progressDialog = new ProgressDialog(this); progressDialog.setTitle("提示"); progressDialog.setCancelable(false); progressDialog.setMessage("正在下載圖片,請耐心等候!"); progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); button1.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { /* * 異步任務、執行下載圖片 */ new MyTask().execute(IMAGE_PATH); } }); } /* * 異步任務:三個參數:第一個地址、第二個、第三個結果 四個步驟:onPreExecute()、 * doInBackground()、onProgressUpdate()、onPostExecute()、沒有參數傳傳進去的時候可以使用void */ public class MyTask extends AsyncTask { /* * onPreExecute()方法在後台操作開始前運行在UI線程上 */ @Override protected void onPreExecute() { super.onPreExecute(); progressDialog.show(); } /* * doInBackground方法運行在後台並處理後台操作 */ @Override protected byte[] doInBackground(String... params) { HttpClient httpClient = new DefaultHttpClient(); HttpGet httpGet = new HttpGet(params[0]); // 第一個參數即是傳入的文件地址 byte[] result = null; InputStream inputStream = null; // 文件流 ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); try { HttpResponse httpResponse = httpClient.execute(httpGet); long file_length = httpResponse.getEntity().getContentLength();// 文件總長度 int total_length = 0; byte[] data = new byte[1024]; int len = 0; if (httpResponse.getStatusLine().getStatusCode() == 200) { // result = // EntityUtils.toByteArray(httpResponse.getEntity()); inputStream = httpResponse.getEntity().getContent(); while ((len = inputStream.read(data)) != -1) { total_length += len; // 產生刻度,進度 int progress_value = (int) ((total_length / (float) file_length) * 100); publishProgress(progress_value); // 發布刻度單位 outputStream.write(data, 0, len); } } result = outputStream.toByteArray(); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { httpClient.getConnectionManager().shutdown(); } return result; } @Override protected void onProgressUpdate(Integer... values) { super.onProgressUpdate(values); progressDialog.setProgress(values[0]); } /* * 一旦後台操作完畢,onPostExecute()方法就會在UI線程中運行 */ @Override protected void onPostExecute(byte[] result) { super.onPostExecute(result); /* * 將下載的bitmap放置在imagView中去 result就是下載的圖片 */ Bitmap bitmap = BitmapFactory.decodeByteArray(result, 0, result.length); imageView1.setImageBitmap(bitmap); progressDialog.dismiss(); } } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.main, menu); return true; } }
\



  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved