AsynTask 异步任务

标签(空格分隔): AsynTask

  • AsynTask 异步任务
      • Android为解决新线程不能更新UI组件问题提供如下解决方案
      • AsynTask 异步任务分析
        • 代码运行示意效果图
      • 代码分析
        • 初始化代码OnCreate
        • AsyncTASK 异步任务实现代码

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

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

  1. Handler线程之间通讯;
  2. 子线程中再次调用主线程;

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

AsynTask 异步任务分析

代码运行示意效果图:

代码分析

01 初始化代码OnCreate:

@Overrideprotected 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<URL, Integer, Bitmap> {    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);    }}

更多相关文章

  1. 基于ffmpeg的Android播放器开源代码
  2. 代码讲解Android(安卓)Scroller、VelocityTracker
  3. 彻底理解android binder通信架构
  4. Android(安卓)之 Looper Handler Message 之间的关系
  5. 《Android经验分享》周刊第9期
  6. Android开发艺术探索—— 第十一章Android的线程和线程池
  7. android studio 设置编译apk的名称以及配置签名,打包方式
  8. Android(安卓)ActionBar的源代码分析(一)
  9. Android中图像变换Matrix的原理、代码验证和应用(一)

随机推荐

  1. android studio 中使用gradle.properties
  2. android 系统数据库
  3. android中自定义Button,设置不同背景图片
  4. android webview设置以及与h5交互
  5. [Android]取得Dialog中EditText的内容问
  6. Android 判断屏幕开关状态方式总结
  7. Android RecyclerView StaggeredGridLayo
  8. Android 使用意图录制视频
  9. android 简单按键修改
  10. Ubuntu 16.04 配置android 源码开发/编译