如图所示:这是一个带有进度条的下载文件的的案例。
下面上代码:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<ProgressBar
android:layout_marginTop="20dp"
android:id="@+id/progress_horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:max="100"
android:progress="0"
style="@style/Widget.AppCompat.ProgressBar.Horizontal"/>
<Button
android:layout_marginTop="10dp"
android:layout_marginBottom="10dp"
android:id="@+id/down_btn"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/down_file"/>
<TextView
android:id="@+id/text_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
package com.example.asynctaskproject;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
/**
* 1.网络上请求数据,网络/SD卡读写的权限需要开启
* 2.布局我们layout
* 3.下载前
* 4.下载中
* 5.下载后
*/
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private static final String TAG = "MainActivity";
public static final int INIT_PROGRESS = 0;
public static final String APK_URL = "http://download.sj.qq.com/upload/connAssitantDownload/upload/MobileAssistant_1.apk";
public static final String FILE_NAME = "xd.apk";
private Button button;
private TextView textView;
private ProgressBar progressBar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();//初始化视图
setData();//初始化数据
}
/**
* 初始化视图
*/
private void initView() {
button = findViewById(R.id.down_btn);
textView = findViewById(R.id.text_view);
progressBar = findViewById(R.id.progress_horizontal);
button.setOnClickListener(this);//点击下载
}
/**
* 设置数据
*/
private void setData() {
progressBar.setProgress(INIT_PROGRESS);
button.setText(R.string.down_file);
textView.setText(R.string.dowload_text);
}
@Override
public void onClick(View v) {// TODO: 2020/6/1 下载
DownloadAsyncTask asyncTask = new DownloadAsyncTask();
asyncTask.execute(APK_URL);//传参--下载地址
}
/**
* String 入参,可以传个下载地址
* Integer 进度
* Boolean 返回值
*/
public class DownloadAsyncTask extends AsyncTask<String,Integer,Boolean>{
private String filePath;
/**
* 在异步任务之前 ,在主线程中
*/
@Override
protected void onPreExecute() {//可操作ui
super.onPreExecute();
button.setText(R.string.down_loading);
textView.setText(R.string.down_loading);
progressBar.setProgress(INIT_PROGRESS);
}
/**
* 在另外一个线程中处理事件
* @param params 入参
* @return
*/
@Override
protected Boolean doInBackground(String... params) {
if(params != null && params.length>0){
String apkUrl = params[0];
try {
//构造URL
URL url = new URL(apkUrl);
//构造链接
URLConnection urlConnection = url.openConnection();//打开链接
InputStream inputStream = urlConnection.getInputStream();//读到这个下载文件的流
int contentLength = urlConnection.getContentLength();//文件内容的长度
//下载的地址
filePath = Environment.getExternalStorageDirectory()
+ File.separator + FILE_NAME;
//对下载地址进行处理
File apkFile = new File(filePath);
if(apkFile.exists()){
Boolean result = apkFile.delete();
if(!result){
return false;
}
}
//已下载的大小
int downLoadSize = 0;
byte[] bytes = new byte[1024];//定义一个字节数组来作为下载的缓存
int length;//长度
//创建一个输出管道
OutputStream outputStream = new FileOutputStream(filePath);
//不断的写入文件,直接没有了为止
while ((length = inputStream.read(bytes)) != -1){
//写入的放到文件管道里
outputStream.write(bytes,0,length);
//累加写入的大小
downLoadSize += length;
//发送进度
publishProgress(downLoadSize*100/contentLength);
}
inputStream.close();
outputStream.close();
} catch (MalformedURLException e) {
e.printStackTrace();
return false;
} catch (IOException e) {
e.printStackTrace();
return false;
}
}else{
return false;
}
return true;
}
/**
* 也是在主线程中,可以执行结果处理
* @param aBoolean
*/
@Override
protected void onPostExecute(Boolean aBoolean) {
super.onPostExecute(aBoolean);
if(aBoolean){
button.setText("下载完成");
textView.setText("下载完成:"+filePath);
}else{
button.setText("下载失败");
textView.setText("下载失败");
}
}
/**
* 进度产生变化的时候
* @param values
*/
@Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
if(values != null && values.length>0)
progressBar.setProgress(values[0]);
}
}
}