Android笔记(十三)AsyncTask(二)

通过onProgressUpdate()来反馈当前任务的执行进度

一、建立布局,通过点击按钮来执行异步任务。

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <Button
        android:id="@+id/button"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="下载图片" />

    <ImageView
        android:id="@+id/image"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:src="@drawable/ic_launcher" />

</LinearLayout>

二、MainAcitivity
在编写代码之前,需要给任务一个权限来实现网络下载。
在注册文件中加入权限
uses-permission android:name=”android.permission.INTERNET”

public class MainActivity extends ActionBarActivity {

    private Button button;
    private ImageView image;
    private String image_path = "http://img1.3lian.com/img2008/06/019/13.jpg";
    private ProgressDialog dialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        button = (Button) findViewById(R.id.button);
        image = (ImageView) findViewById(R.id.image);
        dialog = new ProgressDialog(this);
        dialog.setMessage("正在下载,请稍候...");
        dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        dialog.setCancelable(false);
        button.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                new Mytask().execute(image_path);
            }
        });
    }

    public class Mytask extends AsyncTask<String, Integer, Bitmap> {

        @Override
        protected Bitmap doInBackground(String... params) {
            // TODO Auto-generated method stub
            HttpClient httpClient = new DefaultHttpClient();
            HttpGet httpGet = new HttpGet(params[0]);
            Bitmap bitmap = null;
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            InputStream input = null;
            try {
                HttpResponse httpResponse = httpClient.execute(httpGet);
                if (httpResponse.getStatusLine().getStatusCode() == 200) {
                    input = httpResponse.getEntity().getContent();
                    long file_length = httpResponse.getEntity()
                            .getContentLength();
                    int len = 0;
                    byte[] data = new byte[1024];
                    int total_length = 0;//已下载长度
                    while ((len = input.read(data)) != -1) {//读取data.length个字节存入data中
                        total_length += len;
                        int value = (int) ((total_length / file_length) * 100);
                        publishProgress(value);//发布进度
                        out.write(data, 0, len);//把data中的从0到len个字节写入out输出流,因为不一定是读取了data.length个字节,实际运行往往有偏差
                    }
                    byte[] result = out.toByteArray();
                    bitmap = BitmapFactory.decodeByteArray(result, 0,
                            result.length);
                }
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } finally {
                if (input != null)
                    try {
                        input.close();
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
            }
            return bitmap;
        }

        @Override
        protected void onPreExecute() {
            // TODO Auto-generated method stub
            super.onPreExecute();
            dialog.show();
        }

        @Override
        protected void onProgressUpdate(Integer... values) {
            // TODO Auto-generated method stub
            super.onProgressUpdate(values);
            dialog.setProgress(values[0]);
        }

        @Override
        protected void onPostExecute(Bitmap result) {
            // TODO Auto-generated method stub
            super.onPostExecute(result);
            dialog.dismiss();
            image.setImageBitmap(result);

        }

    }
    }

三、效果如图所示
这里写图片描述

这里写图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值