2014-02-21 51 views
0

我在我的應用程序中有一個webview。我的一個網頁有一個鏈接,我應該從我的應用程序直接下載一個MP3,所以使用downloadlistener這樣的:下載到Android下載文件夾

mWebView.setDownloadListener(new DownloadListener() { 


      public void onDownloadStart(String url, String userAgent, 
        String contentDisposition, String mimetype, 
        long contentLength) { 



       Intent i = new Intent(Intent.ACTION_VIEW); 
       i.setData(Uri.parse(url)); 
       startActivity(i); 
      } 
     }); 

是對我不好,因爲它實際上donwloading文件之前啓動默認瀏覽器。

有什麼辦法可以自己管理下載到OS下載文件夾,以便在用戶轉到Android菜單中的「下載」選項時顯示它?

回答

0

嘗試用一個異步任務做這樣

mWebView.setDownloadListener(new DownloadListener() {

 public void onDownloadStart(String url, String userAgent, 
       String contentDisposition, String mimetype, 
       long contentLength) { 
     new MyDowloadTask().execute(url); 
     } 
    }); 

如果您MyDownload任務的doInBackground方法是類似的東西:

看到http://www.androidsnippets.com/download-an-http-file-to-sdcard-with-progress-notification

+0

我想我可能沒有強調我的問題的關鍵部分,我知道如何通過異步任務下載,我想要了解的是如何下載,以便操作系統將其識別爲「下載「本身 - 以及如何將其保存到下載文件夾。 – MichelReap

+0

您必須將文件的URL作爲意向傳遞給本機瀏覽器。這是實現你想要的最好的方式。 –

0

你可以這樣做通過不使用DownloadListener。您只需重寫WebViewClient的onPageFinished。如果是「application/octet-stream」,請檢查內容類型。然後通過InputStream處理下載。創建文件,保存並打開。 :)

0

您可以自己下載到下載目錄中自己要求的文件,並存入Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);

下面是一些非功能性的僞代碼應該幫助你對你的方式(但可能會要求您捕捉異常並給出UI線程無法進行網絡活動的錯誤;因此您必須將其嵌入AsyncTask中,如Matthew Fisher所建議的那樣)。

public void onDownloadStart(String url, String userAgent, 
    String contentDisposition, String mimetype, long contentLength) 
{ 
    // Define where we want the output file to go 
    File fileOut = new File(
     Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), 
     "Filename.zip" 
    ); 

    // Request it from the interwebz. 
    HttpClient android = AndroidHttpClient.newInstance(userAgent); 
    HttpResponse fileResponse = android.execute(new HttpGet(url)); 

    // Write the response to the file 
    fileResponse.getEntity().writeTo(new FileOutputStream(fileOut)); 
}