專案諮詢——用AsyncTask下載資料
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();
}
});
}
@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); } }