2013-02-01 37 views
0

我構建/複製了一個下載功能,通過URL獲取圖像和視頻並將它們下載到Android設備。Android SDK - 文件下載速度非常慢

下載小圖片時,這沒有問題。但是,當試圖獲取超過2MB(通過WLAN!)的文件需要從字面上的年齡! 25MB視頻大約需要5分鐘,依此類推。

任何想法可能會出錯?

這裏是我的代碼:

 /* Open a connection to that URL. */ 
     URLConnection ucon = url.openConnection(); 

     /* 
     * Define InputStreams to read from the URLConnection. 
     */ 
     InputStream is = ucon.getInputStream(); 
     BufferedInputStream bis = new BufferedInputStream(is); 

     /* 
     * Read bytes to the Buffer until there is nothing more to read(-1). 
     */ 
     ByteArrayBuffer baf = new ByteArrayBuffer(50); 
     int current = 0; 
     while ((current = bis.read()) != -1) { 
       baf.append((byte) current); 
     } 

     /* Convert the Bytes read to a String. */ 
     FileOutputStream fos = new FileOutputStream(file); 
     fos.write(baf.toByteArray()); 
     fos.close(); 
+0

或許真的與緩衝區大小....使用下載管理器....最好的方式下載 – Navdroid

+0

謝謝,但你能提供一些代碼或鏈接? – Ron

+0

看下面有一個例子 – Navdroid

回答

1

使用下載管理器下載文件

 private long enqueue; 
private DownloadManager dm; 

BroadcastReceiver receiver = new BroadcastReceiver() { 
     @Override 
     public void onReceive(Context context, Intent intent) { 
      String action = intent.getAction(); 


      if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)) { 
       long downloadId = intent.getLongExtra(
         DownloadManager.EXTRA_DOWNLOAD_ID, 0); 
       Query query = new Query(); 
       query.setFilterById(enqueue); 
       Cursor c = dm.query(query); 
       if (c.moveToFirst()) { 
        int columnIndex = c.getColumnIndex(DownloadManager.COLUMN_STATUS); 
        if (DownloadManager.STATUS_SUCCESSFUL == c.getInt(columnIndex)) { 

         Log.e("Download completed","HERE DOWNLOAD COMPLETED"); 
         try 
         { 
                 } 
         catch (Exception e) { 
          // TODO: handle exception 
         } 

        } 
} 
      } 
}}; 

要開始下載使用:

  dm = (DownloadManager)activityContext.getSystemService(activityContext.DOWNLOAD_SERVICE); 
    Request request = new Request(Uri.parse("URL")).setDestinationInExternalPublicDir("DIRECTORY","FILENAME"); 
    enqueue = dm.enqueue(request); 
+1

看起來與此相似;)http://www.vogella.com/blog/2011/06/14/android-downloadmanager-example/ – Ron