MainActivity
package com.example.asynctask;
import android.os.AsyncTask;
import android.os.Bundle;
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.URL;
import java.net.URLConnection;
public class MainActivity extends AppCompatActivity {
public static final int progress = 0;
public static final String APK_URL = "http://download.sj.qq.com/upload/connAssitantDownload/upload/MobileAssistant_1.apk";
private ProgressBar progressBar;
private Button button;
private TextView textView;
private static final String TAG = "MainActivity";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
button = (Button) findViewById(R.id.button);
textView = (TextView) findViewById(R.id.textView);
progressBar.setProgress(progress);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
new Myasynctask().execute("imooc", "good");
}
});
}
public class Myasynctask extends AsyncTask<String, Integer, Boolean> {
String path;
/**
* 开始调用
*/
@Override
protected void onPreExecute() {
super.onPreExecute();
textView.setText("下载中");
button.setText("下载中");
progressBar.setProgress(progress);
}
@Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
progressBar.setProgress(values[0]);
button.setText("下载中:" + values[0] + "%");
}
/**
* 结束时调用
*
* @param aBoolean
*/
@Override
protected void onPostExecute(Boolean aBoolean) {
super.onPostExecute(aBoolean);
if (aBoolean) {
textView.setText("下载完成:" + path);
button.setText("点击下载");
}
}
@Override
protected Boolean doInBackground(String... strings) {
try {
URL url = new URL(APK_URL);
URLConnection urlConnection = url.openConnection();
InputStream inputStream = urlConnection.getInputStream();
path = getExternalFilesDir(null).getPath() + "/" + "imooc.apk";
File file = new File(path);
if (file.exists()) {
file.delete();
}
//获取文件的总长度
int contentLength = urlConnection.getContentLength();
//获取输入流
InputStream in = urlConnection.getInputStream();
byte[] b = new byte[1024];
int DownloadLength = 0; //用于保存实时下载长度
int len = 0;
OutputStream outputStream = new FileOutputStream(path);
while ((len = in.read(b)) > -1) {
outputStream.write(b, 0, len);
DownloadLength += len;
publishProgress(DownloadLength * 100 / contentLength);
}
} catch (IOException e) {
e.printStackTrace();
}
return true;
}
}
}
AndroidManifest.xml
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
activity_main.xml
<?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:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="20dp"
android:orientation="vertical"
tools:context=".MainActivity">
<ProgressBar
android:id="@+id/progressBar"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="match_parent"
android:layout_height="20dp"/>
<Button
android:id="@+id/button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:text="点击下载" />
<TextView
android:id="@+id/textView"
android:layout_marginTop="10dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="准备下载" />
</LinearLayout>
扩展:多文件for循环下载 取消下载
private AsyncTask<String, Integer, Boolean> execute;
//主线程启动AsyncTask
execute = new Myasynctask().execute(APK_URL, APK_URL, APK_URL);
//通过按钮点击取消按钮 按钮监听下的代码
boolean flag = execute.cancel(true);
String str;
if (flag) {
str = "取消成功";
}
else {
str = "取消失败";
}
Toast.makeText(MainActivity.this, str , Toast.LENGTH_LONG).show();
//在doInBackground方法内就可以判断了
if(isCancelled()){
return false;
}