2011-11-29 41 views
0

我試圖從我的應用程序中下載文件。我設置了一個按鈕的onClickListener調用這個方法:試圖從Android應用程序內下載文件

private void downloadFile(String fileUrl, File destDir, String fileName) { 
    try { 
     URL url = new URL(fileUrl); 
     HttpURLConnection connection = (HttpURLConnection) url.openConnection(); 
     connection.setRequestMethod("GET"); 
     connection.setDoOutput(true); 
     connection.connect(); 

     if (destDir.isDirectory() && !destDir.exists()) { 
      destDir.mkdirs(); 
     } 

     FileOutputStream output = new FileOutputStream(new File(destDir.toString() + "/" + fileName)); 

     InputStream input = connection.getInputStream(); 

     byte[] buffer = new byte[1024]; 
     int byteCount = 0; 

     while ((byteCount = input.read(buffer)) != -1) { 
      output.write(buffer, 0, byteCount); 
     } 

     output.close(); 
     input.close(); 
    } catch (IOException e) { 
     Toast.makeText(this, "Error: " + e.getMessage(), Toast.LENGTH_SHORT).show(); 
     Log.e("IOException", "Error: " + e.getMessage(), e); 
    } finally { 
     Toast.makeText(this, "File downloaded: " + fileName, Toast.LENGTH_SHORT).show(); 
    } 
} 

我已經經歷各種主題,但沒有一個似乎想出了一個可用的解決方案。當我使用上面指定的代碼時,似乎沒有任何事情發生。

編輯:該文件將在後臺下載並在完成時顯示一個簡短的祝酒。雖然下載時按鈕似乎被「點擊」。對此有何想法?

感謝您的幫助!

其實我並不需要所有的代碼。我不得不使用類似這樣的:

private void getFile(String url) { 
    try { 
     Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url)); 
     startActivity(intent); 
    } catch (ActivityNotFoundException e) { 
     Toast.makeText(this, "Error: " + e.getMessage(), Toast.LENGTH_SHORT).show(); 
     Log.e("ActivityNotFoundException", "Error: " + e.getMessage(), e); 
    } catch (NullPointerException e) { 
     Toast.makeText(this, "Error: " + e.getMessage(), Toast.LENGTH_SHORT).show(); 
     Log.e("NullPointerException", "Error: " + e.getMessage(), e); 
    } 
} 

這也應該是有益的一些人:

private void openFile(File file) { 
    try { 
     Intent intent = new Intent(Intent.ACTION_VIEW, Uri.fromFile(file)); 
     intent.addCategory(Intent.CATEGORY_BROWSABLE); 
     startActivity(intent); 
    } catch (ActivityNotFoundException e) { 
     Toast.makeText(this, "Error: " + e.getMessage(), Toast.LENGTH_SHORT).show(); 
     Log.e("ActivityNotFoundException", "Error: " + e.getMessage(), e); 
    } catch (NullPointerException e) { 
     Toast.makeText(this, "Error: " + e.getMessage(), Toast.LENGTH_SHORT).show(); 
     Log.e("NullPointerException", "Error: " + e.getMessage(), e); 
    } 
} 
+2

什麼是你的問題? – someUser

回答

0

如果沒有反應,你應該添加一些記錄到你的代碼。

而且你還可以顯示錯誤給用戶,通過調用Toast.makeText(context, ex.getMessage(), Toast.LENGTH_SHORT).show()

更好的應該是展示使用這樣的輔助方法的根源消息:

​​
+0

感謝您的幫助。我編輯了代碼,它將與以下調用示例一起工作:'downloadFile(「http://www.samplepdf.com/sample.pdf」,新文件(Environment.getExternalStorageDirectory()。toString())「sample。 PDF「);' –

相關問題