Android DownloadManager的用法

DownloadManager是Android为开发者提供的一个后台应用组件,它通过Http层进行文件的下载任务.


一、直接操作Content Provider中的Downloads表实现!

    1:使用
         首先要在AndroidManifest.xml中申请访问DownloadManager的权限
         
         添加一个下载任务:
         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); 
  // 加入到下载队列:
 
   Request dwreq=new DownloadManager.Request(uri);  
    
          dwreq.setTitle("Demo");  
          dwreq.setDescription("android-ndk-r6-linux-x86.tar.bz2");  
          dwreq.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS,"android-ndk-r6-linux-x86.tar.bz2");  
          dwreq.setNotificationVisibility(0);  
          dwreq.setShowRunningNotification(true);  
    
          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);  
    
    
     }   
  


你可能感兴趣的:(Android DownloadManager的用法)