AsyncTask

来源:互联网 发布:韦德2016季后赛数据 编辑:程序博客网 时间:2024/06/11 23:39
package com.example.y.asynctaskdemos;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;


//MainActivity

public class MainActivity extends AppCompatActivity {



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


        String url="http://img2.imgtn.bdimg.com/it/u=1963594108,1740490324&fm=26&gp=0.jpg";
       
        new MyAsyncTask(MainActivity.this).execute(url);
         String url2="http://www.edu-hb.com/Upload/NewsImg/201009/28/100928085919xc8j6.jpg";
        new MyAsyncTask2(MainActivity.this).execute(url2);

    }


}






package com.example.y.asynctaskdemos;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

/**
 *在创建一个activity 继承AsyncTask
 */

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


    private LinearLayout ll_progress;
    private ProgressBar pb_progressbar;
    private TextView tv_progressbar;
    private ImageView img;


    public MyAsyncTask(Activity context) {
        ll_progress = (LinearLayout) context.findViewById(R.id.ll_progress);
        pb_progressbar = (ProgressBar) context.findViewById(R.id.pb_progressbar);
        tv_progressbar = (TextView) context.findViewById(R.id.tv_progressbar);
        img = (ImageView) context.findViewById(R.id.img);
    }

    /**
     * ①.之前运行的方法
     */
    @Override
    protected void onPreExecute() {
        ll_progress.setVisibility(View.VISIBLE);
        pb_progressbar.setMax(100);
    }


    /**
     * ②.请求网络的方法(子线程)
     * @param strings
     * @return
     * strings-->是调用execute(url)的路径
     *
     */
    @Override
    protected Bitmap doInBackground(String... strings) {


        try {
            URL url=new URL(strings[0]);

            HttpURLConnection  urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.connect();

            //获取数据总长度
            int zlength = urlConnection.getContentLength();

            //当前字节长度
            int dqlength=0;
            //转换成百分之比进度
            int progress=0;  //当前的数组/总字节数组*100


            int code = urlConnection.getResponseCode();
            if(code==HttpURLConnection.HTTP_OK)
            {

                InputStream inputStream = urlConnection.getInputStream();

                ByteArrayOutputStream outputStream=new ByteArrayOutputStream();
                int len=0;
                byte[] bytes=new byte[1024];
                while((len=inputStream.read(bytes))!=-1)
                {
                    //当前的数组长度=运行的数组长度
                    dqlength+=len;
                    progress = (int) ((float)dqlength / zlength * 100);
                    Thread.sleep(100);

                    //调用设置进度条方法
                    publishProgress(progress);

                    outputStream.write(bytes,0,len);
                }
                //图片工程.把数组转换图片的方法(把输出流转换为数组,偏移量,输出流长度)
              return BitmapFactory.decodeByteArray(outputStream.toByteArray(),0,outputStream.size());
            }


        } catch (Exception e) {
            e.printStackTrace();
        }


        return null;
    }

    /**
     * ④.请求请求网络的方法,用于更新Ui
     * @param bitmap
     *
     * bitmap--->下载方法返回值传过来的参数
     */
    @Override
    protected void onPostExecute(Bitmap bitmap) {
        img.setImageBitmap(bitmap);
        ll_progress.setVisibility(View.GONE);
    }


    /**
     *
     * ③请求过程在
     * @param values
     */

    @Override
    protected void onProgressUpdate(Integer... values) {
        pb_progressbar.setProgress(values[0]);
        tv_progressbar.setText(values[0]+"%");
    }
}