Android 使用 DowanloadManager 实现下载并获取下载进度

本文介绍 Android 使用 DowanloadManager 实现下载并获取下载进度的功能。

  1. package com.koolsee.gallery;
  2. import java.util.ArrayList;
  3. import java.util.List;
  4. import java.util.Timer;
  5. import java.util.TimerTask;
  6. import android.app.Activity;
  7. import android.app.DownloadManager;
  8. import android.app.DownloadManager.Request;
  9. import android.content.BroadcastReceiver;
  10. import android.content.Context;
  11. import android.content.Intent;
  12. import android.content.IntentFilter;
  13. import android.database.ContentObserver;
  14. import android.database.Cursor;
  15. import android.net.Uri;
  16. import android.os.Bundle;
  17. import android.os.Environment;
  18. import android.os.Handler;
  19. import android.util.Log;
  20. import android.view.KeyEvent;
  21. import android.view.MotionEvent;
  22. import android.view.View;
  23. import android.view.View.OnKeyListener;
  24. import android.view.View.OnTouchListener;
  25. import android.widget.AdapterView;
  26. import android.widget.AdapterView.OnItemClickListener;
  27. import android.widget.AdapterView.OnItemSelectedListener;
  28. import android.widget.Button;
  29. import android.widget.ImageView;
  30. import android.widget.TextView;
  31. import com.koolsee.gallery.adapter.RecommendAdapter;
  32. import com.koolsee.gallery.model.Recommend;
  33. import com.koolsee.gallery.widget.GalleryFlow;
  34. /**
  35. * 首页
  36. *
  37. * @author zengxiaotao
  38. */
  39. public class testActivity extends Activity {
  40. private DownloadManager dowanloadmanager = null;
  41. private DownloadChangeObserver downloadObserver;
  42. private long lastDownloadId = 0;
  43. public static final Uri CONTENT_URI = Uri.parse("content://downloads/my_downloads");
  44. @Override
  45. protected void onCreate(Bundle savedInstanceState) {
  46. // TODO Auto-generated method stub
  47. super.onCreate(savedInstanceState);
  48. setContentView(R.layout.test);
  49. String serviceString = Context.DOWNLOAD_SERVICE;
  50. dowanloadmanager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
  51. Uri uri = Uri.parse("http://commonsware.com/misc/test.mp4");
  52. Environment.getExternalStoragePublicDirectory(
  53. Environment.DIRECTORY_DOWNLOADS).mkdir();
  54. lastDownloadId = dowanloadmanager.enqueue(new DownloadManager.Request(uri)
  55. .setAllowedNetworkTypes(DownloadManager.Request.NETWORK_MOBILE | DownloadManager.Request.NETWORK_WIFI)
  56. .setAllowedOverRoaming(false)
  57. .setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "test.mp4"));
  58. registerReceiver(receiver, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
  59. downloadObserver = new DownloadChangeObserver(null);
  60. getContentResolver().registerContentObserver(CONTENT_URI, true, downloadObserver);
  61. }
  62. class DownloadChangeObserver extends ContentObserver {
  63. public DownloadChangeObserver(Handler handler) {
  64. super(handler);
  65. // TODO Auto-generated constructor stub
  66. }
  67. @Override
  68. public void onChange(boolean selfChange) {
  69. queryDownloadStatus();
  70. }
  71. }
  72. private BroadcastReceiver receiver = new BroadcastReceiver() {
  73. @Override
  74. public void onReceive(Context context, Intent intent) {
  75. //这里可以取得下载的id,这样就可以知道哪个文件下载完成了。适用与多个下载任务的监听
  76. Log.v("tag", "" + intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, 0));
  77. queryDownloadStatus();
  78. }
  79. };
  80. private void queryDownloadStatus() {
  81. DownloadManager.Query query = new DownloadManager.Query();
  82. query.setFilterById(lastDownloadId);
  83. Cursor c = dowanloadmanager.query(query);
  84. if(c != null && c.moveToFirst()) {
  85. int status = c.getInt(c.getColumnIndex(DownloadManager.COLUMN_STATUS));
  86. int reasonIdx = c.getColumnIndex(DownloadManager.COLUMN_REASON);
  87. int titleIdx = c.getColumnIndex(DownloadManager.COLUMN_TITLE);
  88. int fileSizeIdx = c.getColumnIndex(DownloadManager.COLUMN_TOTAL_SIZE_BYTES);
  89. int bytesDLIdx = c.getColumnIndex(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR);
  90. String title = c.getString(titleIdx);
  91. int fileSize = c.getInt(fileSizeIdx);
  92. int bytesDL = c.getInt(bytesDLIdx);
  93. // Translate the pause reason to friendly text.
  94. int reason = c.getInt(reasonIdx);
  95. StringBuilder sb = new StringBuilder();
  96. sb.append(title).append("\n");
  97. sb.append("Downloaded ").append(bytesDL).append(" / " ).append(fileSize);
  98. // Display the status
  99. Log.d("tag", sb.toString());
  100. switch(status) {
  101. case DownloadManager.STATUS_PAUSED:
  102. Log.v("tag", "STATUS_PAUSED");
  103. case DownloadManager.STATUS_PENDING:
  104. Log.v("tag", "STATUS_PENDING");
  105. case DownloadManager.STATUS_RUNNING:
  106. // 正在下载,不做任何事情
  107. Log.v("tag", "STATUS_RUNNING");
  108. break;
  109. case DownloadManager.STATUS_SUCCESSFUL:
  110. // 完成
  111. Log.v("tag", "下载完成");
  112. // dowanloadmanager.remove(lastDownloadId);
  113. break;
  114. case DownloadManager.STATUS_FAILED:
  115. // 清除已下载的内容,重新下载
  116. Log.v("tag", "STATUS_FAILED");
  117. dowanloadmanager.remove(lastDownloadId);
  118. break;
  119. }
  120. }
  121. }
  122. @Override
  123. protected void onDestroy() {
  124. // TODO Auto-generated method stub
  125. super.onDestroy();
  126. unregisterReceiver(receiver);
  127. getContentResolver().unregisterContentObserver(downloadObserver);
  128. }
  129. }

(完)