码迷,mamicode.com
首页 > 移动开发 > 详细

android 异步任务AsyncTask

时间:2016-06-24 23:35:30      阅读:294      评论:0      收藏:0      [点我收藏+]

标签:

package com.example.ansyctest;


import java.io.ByteArrayOutputStream;
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 android.app.Activity;
import android.app.Dialog;
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.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
/***
 * AsyncTask
 *     异步任务
 *     一种简单的线程 , 是UI线程更简单, 可以执行在后台, 并将数据发布在UI线程
 * 
 *     是一种围绕在线程和handler的辅助类, 不需要构建线框架
 *  是一中短时间的任务, 
 * 
 *     异步任务被定义为运行在后台的线程, 将结果发布到UI界面
 *         有三个泛型参数
 *         AsyncTask‘s generic types
        The three types used by an asynchronous task are the following:
            Params, the type of the parameters sent to the task upon execution.
            Progress, the type of the progress units published during the background computation.
            Result, the type of the result of the background computation.
        Not all types are always used by an asynchronous task. To mark a type as u
 *         
 * Params: 执行任务时发送的参数类型
 * Progress:后台运算执行的进度单元类型    
 * Result:后台计算结果的类型
 * 
 * 
 * 四个步骤        
 *             (1)onPreExecute()                     在任务执行前调用UI线程, 创建任务
 *             (2)doInBackgroud(Params...)        
 *                 在onPreExecute执行完后李立刻执行这个方法,执行后台运算会执行很长时间
 *                 异步任务的参数被传给这个方法, 然后运算的结果传给(4), 
 *                 还可以使用publishProgress(Progress...)传递一个或多个单位的进度, 在(3)中显示在UI线程            
 *             (3)onProgressUpdate(Params...)
 *                 在执行publishProgress(Progress...)后调用UI线程
 *             (4)onPostExecute(Result)
 *                 当后台运算结束后, 运算的结果被传递到这个方法作为参数
 * 
 * 
 * 
 * @author Administrator
 *
 */
public class MainActivity extends Activity {
    private Button btn;
    private ImageView iv;
    private String imgpath="http://www.gwyoo.com/lunwen/jylw/jyyjlw/201603/623467.html";
            
    
    private ProgressDialog dialog; 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btn = (Button)findViewById(R.id.button1);
        iv = (ImageView)findViewById(R.id.imageView1);
        dialog = new ProgressDialog(this);
        dialog.setMax(100);
        dialog.setTitle("提示");
        dialog.setMessage("下载图片");
        dialog.setCancelable(false); //不让用户取消
        dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);


        btn.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                //执行异步任务
                new MyTask().execute(imgpath);
            }
        }); 
    }


    /***
     *Params 传递数据类型
     *Progress 进度单位类型
     *Result 后台返回结果的类型
     */
    class MyTask extends AsyncTask<String, Integer, byte[]>  {
        @Override
        protected void onPreExecute() {//在任务执行前, 创键任务显示
            super.onPreExecute();
            dialog.show();
        }

        @Override
        protected byte[] doInBackground(String... params) {
            byte[] result = null;
            HttpClient httpClient = new DefaultHttpClient();
            HttpGet httpGet = new HttpGet(params[0]);
            try {
                HttpResponse httpResponse = null;
                ByteArrayOutputStream baos = new  ByteArrayOutputStream();
                
                if (httpClient != null && httpGet != null) {
                     httpResponse = httpClient.execute(httpGet);
                }
                //获取资源的总程度
                long file_length = httpResponse.getEntity().getContentLength();
                //已下载的长度
                long downLength = 0;
                //每次下载的数据
                byte[] data = new byte[1024];
                //每次下载的长度
                int len = 0;
                //判断响应码
                if(httpResponse.getStatusLine().getStatusCode() == 200) {
                    //请求成功,获取数据
                    //result= EntityUtils.toByteArray(httpResponse.getEntity());
                    //获取连接
                    InputStream in = httpResponse.getEntity().getContent();
                    //读取资源
                    while((len=in.read(data)) != -1){
                        downLength += len;
                        int progress_value = (int)((downLength/file_length)*100);
                        //发送进度
                        publishProgress(progress_value);
                        baos.write(data, 0, len);
                    }
                    result = baos.toByteArray();
                }else {
                    Log.i("tag", "Exception");
                }
            } catch (Exception e) {
                e.printStackTrace();
            }finally {
                httpClient.getConnectionManager().shutdown();
            }
            return result;
        }
        @Override
        protected void onProgressUpdate(Integer... values) {//更新UI
            super.onProgressUpdate(values);
            setProgress(values[0]);
        } 
        @Override
        protected void onPostExecute(byte[] result) {
            super.onPostExecute(result);
            //Bitmap bm = BitmapFactory.decodeStream(new ByteArrayInputStream(result));
            if(result == null) {return;}
            Bitmap bm = BitmapFactory.decodeByteArray(result, 0, result.length);
            iv.setImageBitmap(bm);
            //            
            dialog.dismiss();
        } 
    }
}

 

android 异步任务AsyncTask

标签:

原文地址:http://www.cnblogs.com/chengbao/p/5615460.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!