【Android 基础】AsynTask 异步任务

【Android 基础】AsynTask 异步任务_第1张图片
image.png

AsynTask 异步任务

Android机制,不允许子线程更新UI界面,耗时操作需要开辟新的Thread执行;

Android为解决新线程不能更新UI组件问题,提供如下解决方案:

  1. Handler线程之间通讯;

  2. 子线程中再次调用主线程;

    runOnUiThread(new Runnable() {
    @Override
    public void run() {
    
    }
    });
    
  3. AsynTask 异步任务

AsynTask 异步任务分析

代码运行示意效果图:

【Android 基础】AsynTask 异步任务_第2张图片
02.png-25kB

代码分析

01 初始化代码OnCreate:

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


    image = (ImageView) findViewById(R.id.imageView);
    show = (TextView) findViewById(R.id.textView);
    Button asynTask = (Button) findViewById(R.id.btn_Asyn);
    asynTask.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            DownTask task = new DownTask();
            try {
                task.execute(new URL("http://img2.imgtn.bdimg.com/it/u=1698945203,1066999821&fm=11&gp=0.jpg"));
            } catch (MalformedURLException e) {
                e.printStackTrace();
            }
        }
    });

}

02 AsyncTASK 异步任务实现代码

private class DownTask extends AsyncTask {

    ProgressDialog progressDialog;
    Bitmap bitmap;
    int curDownSize;

    @Override
    //Asyn异步任务后台执行前初始化操作
    protected void onPreExecute() {
        Log.d(TAG, "onPreExecute01: ");
        super.onPreExecute();
        progressDialog = new ProgressDialog(MainActivity.this);
        Log.d(TAG, "onPreExecute: 01");
        //设置对话框标题
        progressDialog.setTitle("下载任务对话框");
        Log.d(TAG, "onPreExecute: 02");
        //设置对话框内容
        progressDialog.setMessage("下载任务正在执行中...");
        Log.d(TAG, "onPreExecute: 03");
        //设置对话框按钮取消
        progressDialog.setCancelable(false);
        Log.d(TAG, "onPreExecute: 04");
        //设置对话框进度条最大值
        progressDialog.setMax(100);
        Log.d(TAG, "onPreExecute: 05");
        //设置对话框进度条风格
        progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        Log.d(TAG, "onPreExecute: 06");
        //设置对话框的进度条是否显示进度
        progressDialog.setIndeterminate(false);
        Log.d(TAG, "onPreExecute: 07");
        progressDialog.show();
        Log.d(TAG, "onPreExecute: 08");
        KLog.d();
    }

    @Override
    //Asyn异步任务后台开辟新线程执行任务,不能更新UI界面,需通过publishProgress()
    //函数将更新界面的值传递给onProgressUpdate函数
    protected Bitmap doInBackground(URL... params) {
        Log.d(TAG, "doInBackground02: ");
        URL url = params[0];
        int total = 0;
        URLConnection connection = null;
        BufferedInputStream bufferedInputStream = null;
        try {
            //上报链接请求
            connection = params[0].openConnection();
            //字节输入流
            InputStream inputStream = connection.getInputStream();
            //字节缓冲输入流
            bufferedInputStream = new BufferedInputStream(inputStream);
            //计算文件的总大小
            total = connection.getContentLength();
            Log.d(TAG, "doInBackground: total =" + total);
            byte[] bytes = new byte[1024];
            int hasRead = 0;
            //数组cache输出流
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            Log.d(TAG, "doInBackground:inputStream.read(bytes)= ");
            while ((hasRead = bufferedInputStream.read(bytes)) != -1) {
                //curDownSize 实时读取文件大小
                curDownSize += hasRead;
                Log.d(TAG, "doInBackground: curDownSize=" + curDownSize);
                //发送文件下载的百分比
                publishProgress((int) curDownSize * 100 / total);
                Log.d(TAG, "doInBackground: " + (int) curDownSize * 100 / total);
                //读取一个缓冲流,就实时写入一个缓冲流
                bos.write(bytes, 0, hasRead);
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            //数据流转换为bitmap ByteArrayOutputStream.toByteArray()方法
            bitmap = BitmapFactory.decodeByteArray(bos.toByteArray(), 0, bos.toByteArray().length);
            //关闭打开的数据流,先打开的后关闭,后打开的先关闭
            fis.close();
            bos.close();
            inputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return bitmap;
    }

    @Override
    //接收doInBackground传递过来的数据,实时更新UI
    protected void onProgressUpdate(Integer... values) {
        Log.d(TAG, "onProgressUpdate03: ");
        super.onProgressUpdate(values);
        progressDialog.setProgress(values[0]);
        show.setText(String.valueOf(values[0]));
    }

    @Override
    //最后执行的函数
    protected void onPostExecute(Bitmap bitmap) {
        Log.d(TAG, "onPostExecute04: ");
        super.onPostExecute(bitmap);
        progressDialog.dismiss();
        image.setImageBitmap(bitmap);
    }

}

你可能感兴趣的:(【Android 基础】AsynTask 异步任务)