代码改变世界

AsyncTask(异步任务)下载网络图片

2013-12-18 15:10  广科大坏人蜀黍  阅读(310)  评论(0)    收藏  举报
package com.example.myasynctask02;

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 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.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

public class MainActivity extends Activity {

    Button button;
    ImageView imageView;
    TextView textView;
    ProgressDialog progressDialog;
    String image_path;
    @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);
        textView=(TextView) findViewById(R.id.textView1);
        
        progressDialog=new ProgressDialog(this);
        progressDialog.setTitle("提示信息:");
        progressDialog.setMessage("正在下载。。。");
        progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
    //    progressDialog.setCancelable(false);//是否可以撤销进度条(主要指通过Back键取消),Home键回到桌面,依然会后台下载。
        image_path="http://b.hiphotos.baidu.com/image/w%3D2048/sign=1a560359f31fbe091c5ec4145f580d33/64380cd7912397ddc0d9a42b5882b2b7d0a28778.jpg";
        
        
        button.setOnClickListener(new View.OnClickListener() {
            
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                new MyTask().execute(image_path);
            }
        });
    }
    class MyTask extends AsyncTask<String, Integer, Bitmap>{

        @Override
        protected void onPreExecute() {//将在执行后台耗时操作前被调用。
            //通常该方法用于完成一些初始化的准备工作,例如:在界面上显示进度条
            // TODO Auto-generated method stub
            super.onPreExecute();
            progressDialog.show();
        }
        
        @Override
        protected void onProgressUpdate(Integer... values) {
            // TODO Auto-generated method stub
            super.onProgressUpdate(values);
            progressDialog.setProgress(values[0]);
        }
        
        
        /**
         * 后台线程将要完成的任务。可以调用publishProgress方法更新任务的执行进度
         */
        @Override
        protected Bitmap doInBackground(String... params) {//params 启动任务执行的输入参数param[0]指new MyTask().execute(image_path);中的image_path
            // TODO Auto-generated method stub
            Bitmap bitmap=null;
            HttpClient httpClient=new DefaultHttpClient();
            HttpGet httpGet=new HttpGet(params[0]);//param[0]:image_path
            ByteArrayOutputStream byteArrayOutputStream=new ByteArrayOutputStream();
            InputStream inputStream = null;
            try {
                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;//已读取的长度
                    while((len=inputStream.read(data))!=-1){
                        total_length+=len;
                        int values=(int)(total_length/(float)file_length*100);
                        publishProgress(values);
                        byteArrayOutputStream.write(data, 0, len);
                        System.out.println("len="+len);
                    }
                    byte[] result=byteArrayOutputStream.toByteArray();
                    bitmap=BitmapFactory.decodeByteArray(result, 0, result.length);
                    Log.i("zqm", "file_length"+file_length);
                    System.out.println("result.length="+result.length);
                    Log.i("zqm", "result.length="+result.length);
                }
            } catch (ClientProtocolException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                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);
            imageView.setImageBitmap(result);
        //    textView.setText(result.getRowBytes()+"");
            progressDialog.dismiss();
            
            Log.i("zqm","onPostExecute");
        }
        
    }

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

以上为MainActivity代码。

<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_above="@+id/button1"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="185dp"
        android:src="@drawable/ic_launcher" />

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_above="@+id/button1"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="73dp"
        android:text="Large Text"
        android:textAppearance="?android:attr/textAppearanceLarge" />

</RelativeLayout>

以上为res/layout的activity_main.xml布局文件的代码,TextView无实际意义。