public class AsyncTaskTwoActivity extends AppCompatActivity {
private TextView info;
private ProgressBar progressBar;
private @SuppressLint(“StaticFieldLeak”) AsyncTask<String, Integer, File> asyncTask;
@Override protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_asynctask_two);
info = findViewById(R.id.info);
progressBar = findViewById(R.id.progress);
findViewById(R.id.download).setOnClickListener(new View.OnClickListener() {
@Override public void onClick(View v) {
download();
}
});
}
String apkUrl = “https://dldir1.qq.com/weixin/android/weixin673android1360.apk”;
@SuppressLint(“StaticFieldLeak”) private void download() {
asyncTask = new AsyncTask<String, Integer, File>() {
//子线程下载
@Override protected File doInBackground(String… strings) {
Log.i(“TEST”, “doInBackground”);
try {
URL url = new URL(strings[0]);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
int responseCode = urlConnection.getResponseCode();
if (responseCode == 200) {
//将流转换成String
//一边读流一边写
//File file = saveFile(urlConnection.getInputStream());
File file = new File(getCacheDir(), "downloadfile.apk");
FileOutputStream fos = new FileOutputStream(file);
InputStream is = urlConnection.getInputStream();
final int totalCount = urlConnection.getContentLength();
byte[] buf = new byte[10240];
int count = 0;
for (int i = is.read(buf); i != -1; i = is.read(buf)) {
//写数据到文件
fos.write(buf, 0, i);
//发布进度
count = count + i;
//当前进度 文件总大小 666666
publishProgress(count, totalCount);
}
//关闭流
fos.flush();
fos.close();
return file;
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
//进度更新了 主线程
@Override protected void onProgressUpdate(Integer... values) {
info.setText(values[0] + " / " + values[1]);
//progressBar.setProgress((int)((100f / values[1]) * values[0]));
progressBar.setProgress((int) ((values[0] * 1.0f / values[1]) * 100));
}
@Override protected void onPreExecute() {
//先于onPostExecute调用
Log.i("TEST", "onPreExecute");
}
//主线程接收
@Override protected void onPostExecute(File file) {
String filePath = file.getAbsolutePath();
Log.i("TEST", "onPostExecute: " + file.getAbsolutePath());
Toast.makeText(AsyncTaskTwoActivity.this, "下载完成:" + file.getAbsolutePath(),
Toast.LENGTH_SHORT).show();
}
}.execute(apkUrl);
}
private File saveFile(InputStream is) throws IOException {
//getCacheDir() 应用缓存目录 ; 文件名
File file = new File(getCacheDir(), “downloadfile.apk”);
//把文件 和 输出流 关联起来
FileOutputStream fos = new FileOutputStream(file);
byte[] buf = new byte[10240];
for (int i = is.read(buf); i != -1; i = is.read(buf)) {
//写数据到文件
fos.write(buf, 0, i);
}
//关闭流
fos.flush();
fos.close();
return file;
}
@Override protected void onDestroy() {
super.onDestroy();
asyncTask.cancel(true);
}
}