安卓多线程编程系列2:异步任务的使用之使用异步任务带有进度的横向滚动条下载网络图片

来源:互联网 发布:下载行者软件 编辑:程序博客网 时间:2024/05/16 17:29

异步任务是多线程编程中经常使用的一种方式,这里我们介绍一下使用异步任务带有进度的下载网络图片的使用方法。

整体思路:在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;@Overrideprotected 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() {@Overridepublic void onClick(View arg0) {// TODO Auto-generated method stubnew MyTask().execute(image_path);}});}public class MyTask extends AsyncTask<String, Integer, Bitmap>{@Overrideprotected void onPreExecute() {// TODO Auto-generated method stubsuper.onPreExecute();dialog.show();}@Overrideprotected void onProgressUpdate(Integer... values) {// TODO Auto-generated method stubsuper.onProgressUpdate(values);dialog.setProgress(values[0]);//进度条更新}@Overrideprotected Bitmap doInBackground(String... params) {// TODO Auto-generated method stubBitmap 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 exceptione.printStackTrace();}finally{if(inputStream!=null){try {inputStream.close();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}return bitmap;}@Overrideprotected void onPostExecute(Bitmap result) {// TODO Auto-generated method stubsuper.onPostExecute(result);dialog.dismiss();imageView.setImageBitmap(result);}}@Overridepublic 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;}}



1 0
原创粉丝点击