| onProgressUpdate(Progress values):在主线程中更新当前下载进度 onPostExecute(Result result):通知最终的下载结果,回调操作 execute(Parames…params)::触发执行异步线程任务 三,异步加载网络图片的核心代码 
 布局文件,一个ImageView和ProgressBar,ProgressBar控件是实现加载的效果 
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="16dp">
    <ImageView
        android:id="@+id/image"
        android:layout_width="match_parent"
        android:layout_height="300dp" />
    
    <ProgressBar
        android:id="@+id/progress_bar"
        android:visibility="gone"
        android:layout_centerInParent="true"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
</RelativeLayout> 
 主活动 
package com.yaninfo;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.ProgressBar;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.net.URL;
import java.io.InputStream;
import java.net.URLConnection;
/**
 * @Author: zhangyan
 * @Date: 2019/4/4 11:04
 * @Description: 图片异步加载
 * @Version: 1.0
 */
public class ImageActivity extends Activity {
    private ImageView mImageView;
    private ProgressBar mProgressBar;
    private static String URL = "http://img.mp.itc.cn/upload/20170221/579c7d2769fd4ee2b6d4c460cd1c4b9c_th.jpg";
    private MyTask mTask = new MyTask();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.image_layout);
        // 初始化
        init();
        // 执行线程
        mTask.execute(URL);
    }
    /**
     * 初始化控件
     */
    private void init() {
        mImageView = findViewById(R.id.image);
        mProgressBar = findViewById(R.id.progress_bar);
    }
    /**
     * 开启异步线程
     */
    private class MyTask extends AsyncTask<String, Void, Bitmap> {
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            mProgressBar.setVisibility(View.VISIBLE);
        }
        /**
         * 更新UI
         *
         * @param bitmap
         */
        @Override
        protected void onPostExecute(Bitmap bitmap) {
            super.onPostExecute(bitmap);
            mImageView.setImageBitmap(bitmap);
            mProgressBar.setVisibility(View.GONE);
        }
        /**
         * 执行耗时操作
         *
         * @param params
         * @return
         */
        @Override
        protected Bitmap doInBackground(String... params) {
            // 从params可变长数组中获取传递进来的url参数
            String url = params[0];
            Bitmap bitmap = null;
            URLConnection connection;
            InputStream in = null;
            BufferedInputStream buffer = null;
            try {
                connection = new URL(url).openConnection();
                in = connection.getInputStream();
                buffer = new BufferedInputStream(in);
                // 输入流转化为bitmap对象,利用decodeStream方法来解析输入流
                Thread.sleep(2000);
                bitmap = BitmapFactory.decodeStream(buffer);
            } catch (IOException e) {
                e.printStackTrace();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                try {
                    in.close();
                    buffer.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            // 返回bitmap
            return bitmap;
        }
    }
} 
 这里我们在doInBackground方法中定义了一个Bitmap 对象来存图片,最后Bitmap对象会传给onPostExecute方法用来更新UI。这里怎么传参? 想深入了解的小老弟,可以看一下源码很简单的! 四,模拟进度条的核心代码 
 布局文件,这里定义了两个Button,一个TextView控件和ProgressBar。采用的是RelativeLayout 布局 
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    tools:context=".MainActivity">
    <Button
        android:layout_centerInParent="true"
        android:id="@+id/loading"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="点我加载"/>
    <TextView
        android:id="@+id/text"
        android:layout_below="@+id/loading"
        android:layout_centerInParent="true"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="还没开始加载!" />
    <ProgressBar
        android:id="@+id/progress_bar"
        android:layout_below="@+id/text"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:progress="0"
        android:max="100"
        style="?android:attr/progressBarStyleHorizontal"/>
    <Button
        android:layout_below="@+id/progress_bar"
        android:layout_centerInParent="true"
        android:id="@+id/cancel"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="取消加载"/>
</RelativeLayout> 
 线程类 
package com.yaninfo;
import android.os.AsyncTask;
import android.widget.ProgressBar;
import android.widget.TextView;
/**
 * @Author: zhangyan
 * @Date: 2019/4/4 9:58
 * @Description: AsyncTask线程任务进度条加载
 * @Version: 1.0
 */
public class MyTask extends AsyncTask<String, Integer, String> {
    private TextView text;
    private ProgressBar progressBar;
    /**
     * 构造方法
     *
     * @param text
     * @param progressBar
     */
    public MyTask(TextView text, ProgressBar progressBar) {
        this.text = text;
        this.progressBar = progressBar;
    }
    /**
     * 执行线程任务前的操作
     */
    @Override
    protected void onPreExecute() {
        text.setText("加载中");
    }
    /**
     * 接收输入参数、执行任务中的耗时操作、返回线程任务执行的结果
     *
     * @param params
     * @return
     */
    @Override
    protected String doInBackground(String... params) {
        try {
            for (int count = 0; count < 100; count++) {
            
                // 改变count,之后传给onProgressUpdate中的progresses用于更新进度条
                publishProgress(count);
                // 休眠100毫秒
                Thread.sleep(100);
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return null;
    }
    /**
     * 在主线程 显示线程任务执行的进度
     *
     * @param progresses
     */
    @Override
    protected void onProgressUpdate(Integer... progresses) {
        int progress = progresses[0];
        progressBar.setProgress(progress);
        text.setText("loading..." + progress + "%");
    }
    /**
     * 接收线程任务执行结果、将执行结果显示到UI组件
     *
     * @param result
     */
    @Override
    protected void onPostExecute(String result) {
        text.setText("加载完毕");
    }
    /**
     * 将异步任务设置为:取消状态
     */
    @Override
    protected void onCancelled() {
        text.setText("已取消");
        progressBar.setProgress(0);
    }
} 
 这里在doInBackground方法中用for循环模拟了更新进度条的逻辑,然后在执行相关UI操作,很简单有没有!! 主活动 主活动 
package com.yaninfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
### **写在最后**
最后我想说:对于程序员来说,要学习的知识内容、技术有太多太多,要想不被环境淘汰就只有不断提升自己,**从来都是我们去适应环境,而不是环境来适应我们!**
这里附上上述的技术体系图相关的几十套**腾讯、头条、阿里、美团等公司2021年的面试题**,把技术点整理成了视频和PDF(实际上比预期多花了不少精力),包含**知识脉络 + 诸多细节**,由于篇幅有限,这里以图片的形式给大家展示一部分。
**相信它会给大家带来很多收获:**


**[CodeChina开源项目:《Android学习笔记总结+移动架构视频+大厂面试真题+项目实战源码》](https://codechina.csdn.net/m0_60958482/android_p7)**
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
### **写在最后**
最后我想说:对于程序员来说,要学习的知识内容、技术有太多太多,要想不被环境淘汰就只有不断提升自己,**从来都是我们去适应环境,而不是环境来适应我们!**
这里附上上述的技术体系图相关的几十套**腾讯、头条、阿里、美团等公司2021年的面试题**,把技术点整理成了视频和PDF(实际上比预期多花了不少精力),包含**知识脉络 + 诸多细节**,由于篇幅有限,这里以图片的形式给大家展示一部分。
**相信它会给大家带来很多收获:**
[外链图片转存中...(img-LQXSyMwt-1630827377337)]
[外链图片转存中...(img-WgLS12IO-1630827377339)]
**[CodeChina开源项目:《Android学习笔记总结+移动架构视频+大厂面试真题+项目实战源码》](https://codechina.csdn.net/m0_60958482/android_p7)**
> 当程序员容易,当一个优秀的程序员是需要不断学习的,从初级程序员到高级程序员,从初级架构师到资深架构师,或者走向管理,从技术经理到技术总监,每个阶段都需要掌握不同的能力。早早确定自己的职业方向,才能在工作和能力提升中甩开同龄人。
 |