Downloadmanager in android

rowandjj發表於2015-11-19

Downloadmanager使用

DownloadManager是android提供的一個下載管理器

缺點:不支援斷點續傳

使用方法:

  1. 建立例項:

    DownloadManager manager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
  2. 建立下載任務:

    DownloadManager.Request request = new DownloadManager.Request(Uri.parse(URL));
    //指定儲存地址
    request.setDestinationInExternalPublicDir("chuyi", "meizhi.apk");
    //設定允許下載的網路狀況
    request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI);
    //設定通知欄的行為
    request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
    //通過id唯一標識此下載任務
    long id = manager.enqueue(request);
  3. 刪除下載任務:

    manager.remove(id);
  4. 查詢下載任務:

    DownloadManager.Query query = new DownloadManager.Query();
    query.setFilterById(id);
    Cursor cursor = manager.query(query);
    
    if(cursor.moveToFirst()){
        String filename = cursor.getString(cursor.getColumnIndex(DownloadManager.COLUMN_LOCAL_FILENAME));
        String fileUri = cursor.getString(cursor.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));
        Toast.makeText(context,"下載完成...name:"+filename+",uri:"+fileUri,Toast.LENGTH_SHORT).show();
    }else {
      //TODO
    }
    cursor.close();
  5. 查詢下載進度:

    DownloadManager.Query query = new DownloadManager.Query().setFilterById(downloadId);
    Cursor c = null;
    try {
        c = downloadManager.query(query);
        if (c != null && c.moveToFirst()) {
            int downloadedBytes = c.getInt(c.getColumnIndexOrThrow(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR));
            int totalBytes = c.getInt(c.getColumnIndexOrThrow(DownloadManager.COLUMN_TOTAL_SIZE_BYTES));
            int state = c.getInt(c.getColumnIndex(DownloadManager.COLUMN_STATUS));
        }
    } finally {
        if (c != null) {
            c.close();
        }
    }
    
  6. 監聽下載結束通知:

    可以通過接收DownloadManager.ACTION_DOWNLOAD_COMPLETE廣播來監聽下載結束的通知

    IntentFilter filter = new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE);
        mReceiver = new BroadcastReceiver(){
          public void onReceive(Context c,Intent i){
              long downId = i.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID,-1);
          }
        }
        context.registerReceiver(mReceiver,filter);
  7. 監聽下載進度:

    主要有三種方案:1.FileReceiver 2.ContentObserver 3.定時任務

    class DownloadChangeObserver extends ContentObserver {
    
    public DownloadChangeObserver(){
        super(handler);
    }
    
    @Override
    public void onChange(boolean selfChange) {
        //查詢進度
    }
    
    }
    //in activity
    private DownloadChangeObserver downloadObserver;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.download_manager_demo);
    ……
    downloadObserver = new DownloadChangeObserver();
    }
    
    @Override
    protected void onResume() {
        super.onResume();
        /** observer download change **/
        getContentResolver().registerContentObserver(DownloadManagerPro.CONTENT_URI, true,
                                                     downloadObserver);
    }
    
    @Override
    protected void onPause() {
        super.onPause();
        getContentResolver().unregisterContentObserver(downloadObserver);
    }

    上面這種做法可能對效能有些損耗,因為會不斷觸發onChange

    推薦使用ScheduledExecutorService

    public static ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(3);
    Runnable command = new Runnable() {
    
        @Override
        public void run() {
            updateView();
        }
    };
    scheduledExecutorService.scheduleAtFixedRate(command, 0, 3, TimeUnit.SECONDS);

    參考資料:

    1. http://www.trinea.cn/android/android-downloadmanager/
    2. http://www.trinea.cn/android/android-downloadmanager/
    3. https://github.com/Trinea/android-common/blob/master/src/cn/trinea/android/common/util/DownloadManagerPro.java

相關文章