歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Android中使用AsyncTask做下載進度條

Android中使用AsyncTask做下載進度條

日期:2017/3/1 10:37:09   编辑:Linux編程

AsyncTask是個不錯的東西,可以使用它來做下載進度條。代碼講解如下:

  1. package com.example.downloadfile;
  2. import java.io.File;
  3. import java.io.FileOutputStream;
  4. import java.io.InputStream;
  5. import java.net.HttpURLConnection;
  6. import java.net.URL;
  7. import Android.app.Activity;
  8. import android.app.Dialog;
  9. import android.app.ProgressDialog;
  10. import android.os.AsyncTask;
  11. import android.os.Bundle;
  12. import android.os.Environment;
  13. import android.util.Log;
  14. import android.widget.TextView;
  15. public class DownloadFile extends Activity {
  16. public static final String LOG_TAG = "test";
  17. private ProgressDialog mProgressDialog;
  18. public static final int DIALOG_DOWNLOAD_PROGRESS = 0;
  19. File rootDir = Environment.getExternalStorageDirectory();
  20. //定義要下載的文件名
  21. public String fileName = "test.jpg";
  22. public String fileURL = "https://lh4.googleusercontent.com/-HiJOyupc-tQ/TgnDx1_HDzI/AAAAAAAAAWo/DEeOtnRimak/s800/DSC04158.JPG";
  23. @Override
  24. public void onCreate(Bundle savedInstanceState)
  25. {
  26. super.onCreate(savedInstanceState);
  27. setContentView(R.layout.main);
  28. TextView tv = new TextView(this);
  29. tv.setText("Android Download File With Progress Bar");
  30. //檢查下載目錄是否存在
  31. checkAndCreateDirectory("/mydownloads");
  32. //執行asynctask
  33. new DownloadFileAsync().execute(fileURL);
  34. }
  35. class DownloadFileAsync extends AsyncTask<String, String, String> {
  36. @Override
  37. protected void onPreExecute() {
  38. super.onPreExecute();
  39. showDialog(DIALOG_DOWNLOAD_PROGRESS);
  40. }
  41. @Override
  42. protected String doInBackground(String... aurl) {
  43. try {
  44. //連接地址
  45. URL u = new URL(fileURL);
  46. HttpURLConnection c = (HttpURLConnection) u.openConnection();
  47. c.setRequestMethod("GET");
  48. c.setDoOutput(true);
  49. c.connect();
  50. //計算文件長度
  51. int lenghtOfFile = c.getContentLength();
  52. FileOutputStream f = new FileOutputStream(new File(rootDir + "/my_downloads/", fileName));
  53. InputStream in = c.getInputStream();
  54. //下載的代碼
  55. byte[] buffer = new byte[1024];
  56. int len1 = 0;
  57. long total = 0;
  58. while ((len1 = in.read(buffer)) > 0) {
  59. total += len1; //total = total + len1
  60. publishProgress("" + (int)((total*100)/lenghtOfFile));
  61. f.write(buffer, 0, len1);
  62. }
  63. f.close();
  64. } catch (Exception e) {
  65. Log.d(LOG_TAG, e.getMessage());
  66. }
  67. return null;
  68. }
  69. protected void onProgressUpdate(String... progress) {
  70. Log.d(LOG_TAG,progress[0]);
  71. mProgressDialog.setProgress(Integer.parseInt(progress[0]));
  72. }
  73. @Override
  74. protected void onPostExecute(String unused) {
  75. //dismiss the dialog after the file was downloaded
  76. dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
  77. }
  78. }
  79. public void checkAndCreateDirectory(String dirName){
  80. File new_dir = new File( rootDir + dirName );
  81. if( !new_dir.exists() ){
  82. new_dir.mkdirs();
  83. }
  84. }
  85. @Override
  86. protected Dialog onCreateDialog(int id) {
  87. switch (id) {
  88. case DIALOG_DOWNLOAD_PROGRESS: //we set this to 0
  89. mProgressDialog = new ProgressDialog(this);
  90. mProgressDialog.setMessage("Downloading file...");
  91. mProgressDialog.setIndeterminate(false);
  92. mProgressDialog.setMax(100);
  93. mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
  94. mProgressDialog.setCancelable(true);
  95. mProgressDialog.show();
  96. return mProgressDialog;
  97. default:
  98. return null;
  99. }
  100. }
  101. }
Copyright © Linux教程網 All Rights Reserved