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

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

实现代码:

package com.koolsee.gallery;
 
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
 
import android.app.Activity;
import android.app.DownloadManager;
import android.app.DownloadManager.Request;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.ContentObserver;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnKeyListener;
import android.view.View.OnTouchListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
 
import com.koolsee.gallery.adapter.RecommendAdapter;
import com.koolsee.gallery.model.Recommend;
import com.koolsee.gallery.widget.GalleryFlow;
 
/**
 * 首页
 *
 * @author zengxiaotao
 */
public class testActivity extends Activity {
 private DownloadManager dowanloadmanager = null;
 private DownloadChangeObserver downloadObserver;
 private long lastDownloadId = 0;
 public static final Uri CONTENT_URI = Uri.parse("content://downloads/my_downloads");
 @Override
 protected void onCreate(Bundle savedInstanceState) {
  // TODO Auto-generated method stub
  super.onCreate(savedInstanceState);
  setContentView(R.layout.test);
  String serviceString = Context.DOWNLOAD_SERVICE;
  dowanloadmanager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
 
  Uri uri = Uri.parse("http://commonsware.com/misc/test.mp4");
  Environment.getExternalStoragePublicDirectory(
   Environment.DIRECTORY_DOWNLOADS).mkdir();
 
  lastDownloadId = dowanloadmanager.enqueue(new DownloadManager.Request(uri)
           .setAllowedNetworkTypes(
            DownloadManager.Request.NETWORK_MOBILE
            | DownloadManager.Request.NETWORK_WIFI)
           .setAllowedOverRoaming(false)
           .setDestinationInExternalPublicDir(
            Environment.DIRECTORY_DOWNLOADS, "test.mp4"));
  registerReceiver(receiver, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
  downloadObserver = new DownloadChangeObserver(null);
  getContentResolver().registerContentObserver(CONTENT_URI, true, downloadObserver);
 }
 class DownloadChangeObserver extends ContentObserver {
 
  public DownloadChangeObserver(Handler handler) {
   super(handler);
   // TODO Auto-generated constructor stub
  }
 
  @Override
  public void onChange(boolean selfChange) {
   queryDownloadStatus();
  }
 }
  
 private BroadcastReceiver receiver = new BroadcastReceiver() {
  @Override
  public void onReceive(Context context, Intent intent) {
   //这里可以取得下载的id,这样就可以知道哪个文件下载完成了。适用与多个下载任务的监听
   Log.v("tag", "" + intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, 0));
   queryDownloadStatus();
  }
 };
 
 private void queryDownloadStatus() {
  DownloadManager.Query query = new DownloadManager.Query();
  query.setFilterById(lastDownloadId);
  Cursor c = dowanloadmanager.query(query);
  if(c != null && c.moveToFirst()) {
   int status = c.getInt(c.getColumnIndex(DownloadManager.COLUMN_STATUS));
 
   int reasonIdx = c.getColumnIndex(DownloadManager.COLUMN_REASON);
   int titleIdx = c.getColumnIndex(DownloadManager.COLUMN_TITLE);
   int fileSizeIdx =
    c.getColumnIndex(DownloadManager.COLUMN_TOTAL_SIZE_BYTES);
   int bytesDLIdx =
    c.getColumnIndex(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR);
   String title = c.getString(titleIdx);
   int fileSize = c.getInt(fileSizeIdx);
   int bytesDL = c.getInt(bytesDLIdx);
 
   // Translate the pause reason to friendly text.
   int reason = c.getInt(reasonIdx);
   StringBuilder sb = new StringBuilder();
   sb.append(title).append("\n");
   sb.append("Downloaded ").append(bytesDL).append(" / " ).append(fileSize);
 
   // Display the status
   Log.d("tag", sb.toString());
   switch(status) {
   case DownloadManager.STATUS_PAUSED:
    Log.v("tag", "STATUS_PAUSED");
   case DownloadManager.STATUS_PENDING:
    Log.v("tag", "STATUS_PENDING");
   case DownloadManager.STATUS_RUNNING:
    // 正在下载,不做任何事情
    Log.v("tag", "STATUS_RUNNING");
    break;
   case DownloadManager.STATUS_SUCCESSFUL:
    // 完成
    Log.v("tag", "下载完成");
    // dowanloadmanager.remove(lastDownloadId);
    break;
   case DownloadManager.STATUS_FAILED:
    // 清除已下载的内容,重新下载
    Log.v("tag", "STATUS_FAILED");
    dowanloadmanager.remove(lastDownloadId);
    break;
   }
  }
 }
 
 @Override
 protected void onDestroy() {
  // TODO Auto-generated method stub
  super.onDestroy();
  unregisterReceiver(receiver);
  getContentResolver().unregisterContentObserver(downloadObserver);
 }
}

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!