程序员人生 网站导航

Android学习笔记之AsyncTask实现文件下载任务

栏目:综合技术时间:2015-01-21 08:43:56

(1)该文件下载主要演示异步任务下载图片

(2)布局代码以下:1个ImageView用于寄存下载的图片,Button用于开始异步任务下载

<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" > <ImageView android:id="@+id/imageView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_alignParentTop="true" android:layout_marginLeft="141dp" android:layout_marginTop="135dp" /> <Button android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentBottom="true" android:layout_alignRight="@+id/imageView1" android:layout_marginBottom="80dp" android:text="网页下载图片" /> </RelativeLayout>

(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); } }); } /* * 异步任务:3个参数、4个步骤onPreExecute()、 * doInBackground()、onProgressUpdate()、onPostExecute()、没有参数传传进去的时候可使用void */ public class MyTask extends AsyncTask<String, Integer, byte[]> { /* * 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); } /* * 1旦后台操作终了,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)显示带刻度条的文件下载:

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⑴50114151438.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); } }); } /* * 异步任务:3个参数:第1个地址、第2个、第3个结果 4个步骤:onPreExecute()、 * doInBackground()、onProgressUpdate()、onPostExecute()、没有参数传传进去的时候可使用void */ public class MyTask extends AsyncTask<String, Integer, byte[]> { /* * 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]); // 第1个参数即是传入的文件地址 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)) != ⑴) { 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]); } /* * 1旦后台操作终了,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; } }




------分隔线----------------------------
------分隔线----------------------------

最新技术推荐