Android DownloadManager的用法

來源:互聯網
上載者:User

DownloadManager是Android為開發人員提供的一個後台應用組件,它通過Http層進行檔案的下載任務.


一、直接操作Content Provider中的Downloads表實現!

    1:使用
         首先要在AndroidManifest.xml中申請訪問DownloadManager的許可權
          <permission android:name="android.permission.ACCESS_DOWNLOAD_MANAGER"/>
         添加一個下載任務:
         ContentValues values = new ContentValues();
         values.put(Downloads.URI, url);//指定
        values.put(Downloads.COOKIE_DATA, cookie);//如果下載Server需要cookie,設定cookie
        values.put(Downloads.VISIBILITY,Downloads.VISIBILITY_HIDDEN);//設定下載提示是否在螢幕頂部顯示
        values.put(Downloads.NOTIFICATION_PACKAGE, getPackageName());//設定下載完成之後回調的包名
        values.put(Downloads.NOTIFICATION_CLASS, DownloadCompleteReceiver.class.getName());//設定下載完成之後負責接收的Receiver,這個類要繼承BroadcastReceiver     
        values.put(Downloads.DESTINATION,save_path);//設定下載到的路徑,這個需要在Receiver裡自行處理
        values.put(Downloads.TITLE,title);//設定下載任務的名稱
        this.getContentResolver().insert(Downloads.CONTENT_URI, values);//將其插入到DownloadManager的資料庫中,資料庫會觸發修改事件,啟動下載任務

   2:如何為DownloadManager設定代理,比如Wap
             values.put(Downloads.PROXY_HOST,"10.0.0.172");
            values.put(Downloads.PROXY_PORT,"80");

  3:如何在下載過程中監聽下載任務
     可以通過監聽資料庫來實現
    DownloadsChangeObserver mDownloadObserver=new DownloadsChangeObserver(Downloads.CONTENT_URI);
    private class DownloadsChangeObserver extends ContentObserver {
        public DownloadsChangeObserver(Uri uri) {
            super(new Handler());
        }
        @Override
        public void onChange(boolean selfChange) {
            //查詢需要監聽的欄位
           //比如要監聽即時下載進度,查看當前下載狀態:是否已經斷開,或者下載失敗等等
           StringBuilder wherequery = new StringBuilder(Downloads.TITLE);
            wherequery.append("=");
            wherequery.append("'");
            wherequery.append(mTitle);
            wherequery.append("'");

           mDownloadCursor =mContext.getContentResolver().query(Downloads.CONTENT_URI, new String[] {Downloads.TITLE, Downloads.STATUS, Downloads.CURRENT_BYTES,}, wherequery.toString(), null,orderBy);        
            int mSizeColunmId=mDownloadCursor.getColumnIndexOrThrow(Downloads.CURRENT_BYTES);   
           mDownloadCursor.moveToFirst();    
            int size=mDownloadCursor.getInt(mSizeColunmId);
       }

  4:如何刪除下載記錄
    private void deleteHistory(String title)//刪除掉指定名稱的下載記錄
    { 
        StringBuilder whereDelete = new StringBuilder(Downloads.TITLE);
        whereDelete.append("=");
        whereDelete.append("'");
        whereDelete.append(str);
        whereDelete.append("'");
        this.getContentResolver().delete(Downloads.CONTENT_URI,whereDelete.toString(), null);

    }   

二、利用API提供的DownloadManager類實現(Since API 9):

  DownloadManger mgr=(DownloadManager)getSystemService(DOWNLOAD_SERVICE);   // 加入到下載隊列:
 
    
      
  1.  Request dwreq=new DownloadManager.Request(uri); 
  2.  
  3.         dwreq.setTitle("Demo"); 
  4.         dwreq.setDescription("android-ndk-r6-linux-x86.tar.bz2"); 
  5.         dwreq.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS,"android-ndk-r6-linux-x86.tar.bz2"); 
  6.         dwreq.setNotificationVisibility(0);
  7.         dwreq.setShowRunningNotification(true); 
  8.  
  9.         lastDownload=mgr.enqueue(dwreq); 

// 查詢下載的狀態


  • public void queryDownloadStatus(View v)  { 
  •  
  •       Runnable queryRunable = new Runnable() { 
  •           long totalsize=0; 
  •           long dowsize=0; 
  •           boolean downok=false; 
  •           Cursor c=null; 
  •  
  •         public void run() { 
  •  
  •             //查詢下載檔案總大小 
  •             totalsize=c.getLong(c.getColumnIndex(DownloadManager.COLUMN_TOTAL_SIZE_BYTES)); 
  •  
  •             Message msg_packsize=new Message(); 
  •             msg_packsize.what=MSG_DWPACKSIZE; 
  •             msg_packsize.arg1=(int) totalsize; 
  •             handler.sendMessage (msg_packsize); 
  •  
  •             while(downok==false){ 
  •                          c=mgr.query(new DownloadManager.Query().setFilterById(lastDownload)); 
  •  
  •                         if (c==null) { 
  •                             //tvdwsize.setText("query=null"); 
  •                         } 
  •                         else { 
  •                             c.moveToFirst(); 
  •                             //查詢已經下載的大小 
  •                             dowsize=c.getLong(c.getColumnIndex(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR)); 
  •                             if(totalsize==dowsize) downok=true; 
  •                         } 
  •  
  •                         Message msg=new Message(); 
  •                         msg.what=MSG_DWSIZE; 
  •                         msg.arg1=(int) dowsize; 
  •                         handler.sendMessage (msg); 
  •  
  •                         try { 
  •                             Thread.sleep(5000); 
  •                         } catch (InterruptedException e) { 
  •                             // TODO Auto-generated catch block 
  •                             e.printStackTrace(); 
  •                         } 
  •                         c.close(); 
  •                 } 
  •             }//run 
  •         }; 
  •  
  •            Thread background = new Thread(queryRunable); 
  •            background.start(); 
  •  
  •     public void delDownloads(View view) { 
  •  
  •         Toast.makeText(this, "delDownloads", Toast.LENGTH_LONG).show(); 
  •         mgr.remove(lastDownload); 
  •  
  •  
  •    }
  • 相關文章

    聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.