2013-06-13 37 views
8

Tôi muốn tải xuống tệp (chẳng hạn như .mp3) từ trang web bằng cách sử dụng webview nhưng vấn đề là Bất cứ khi nào tôi nhấn vào liên kết, nó sẽ mở trình duyệt (Mặc định) xuất hiện trong giây lát trước khi đóng. và không có tệp nào được tải xuống.Tôi làm cách nào để tải xuống tệp bằng cách sử dụng chế độ xem web? (trường hợp này là lạ)

Dưới đây là mã của tôi,

import android.app.Activity; 
import android.content.Intent; 
import android.net.Uri; 
import android.os.Bundle; 
import android.webkit.WebView; 
import android.webkit.WebViewClient; 
import android.webkit.WebChromeClient; 
import android.view.Menu; 
import android.view.View; 
import android.view.View.OnClickListener; 
import android.webkit.DownloadListener; 
import android.widget.Button; 
import android.widget.TextView; 

public class Main extends Activity { 
WebView webview; 
Button bt_search; 
TextView txt_search; 
@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.main); 
    webview = (WebView) findViewById(R.id.webView); 
    webview.setWebChromeClient(new WebChromeClient()); 
    webview.getSettings().setJavaScriptEnabled(true); 
    webview.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); 
     } 
    }); 
    txt_search = (TextView) findViewById(R.id.song); 
    webview.loadUrl("http://www.google.com"); 
    bt_search = (Button) findViewById(R.id.findit); 
    bt_search.setOnClickListener(new OnClickListener() { 
     public void onClick(View v) { 
      String keyword = txt_search.getText().toString().trim(); 
      if (!keyword.equals("")) { 
       webview.loadUrl("MP3 Sites" + keyword + ".html"); 
    } 
    } 
}); 
} 

@Override 
public boolean onCreateOptionsMenu(Menu menu) { 
    // Inflate the menu; this adds items to the action bar if it is present. 
    getMenuInflater().inflate(R.menu.main, menu); 
    return true; 
} 

    } 
+0

Bạn cũng có thể sử dụng này 'Webview' lớp con nơi tập tin tải được xử lý tự động: https://github.com/delight-im/Android-AdvancedWebView – caw

Trả lời

9

Thực hiện một WebViewClient để sử dụng với WebView của bạn. Trong đó, ghi đè phương thức shouldOverrideUrlLoading, nơi bạn nên kiểm tra xem đó có phải là tệp mp3 không, sau đó chuyển URL đó đến DownloadManager hoặc bất kỳ thứ gì bạn đang sử dụng để thực sự tải xuống tệp. Dưới đây là một ý tưởng thô:

// This will handle downloading. It requires Gingerbread, though 
    final DownloadManager manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE); 

    // This is where downloaded files will be written, using the package name isn't required 
    // but it's a good way to communicate who owns the directory 
    final File destinationDir = new File (Environment.getExternalStorageDirectory(), getPackageName()); 
    if (!destinationDir.exists()) { 
     destinationDir.mkdir(); // Don't forget to make the directory if it's not there 
    } 
    webView.setWebViewClient(new WebViewClient() { 
     @Override 
     public boolean shouldOverrideUrlLoading (WebView view, String url) { 
      boolean shouldOverride = false; 
      // We only want to handle requests for mp3 files, everything else the webview 
      // can handle normally 
      if (url.endsWith(".mp3")) { 
       shouldOverride = true; 
       Uri source = Uri.parse(url); 

       // Make a new request pointing to the mp3 url 
       DownloadManager.Request request = new DownloadManager.Request(source); 
       // Use the same file name for the destination 
       File destinationFile = new File (destinationDir, source.getLastPathSegment()); 
       request.setDestinationUri(Uri.fromFile(destinationFile)); 
       // Add it to the manager 
       manager.enqueue(request); 
      } 
      return shouldOverride; 
     } 
    }); 
+0

Cảm ơn bạn rất nhiều cho câu trả lời, nhưng nếu bạn quan tâm, xin vui lòng cho tôi một ví dụ về phương pháp đó. Tôi là người mới chơi trong Java. –

+0

Tôi đã thêm một ví dụ mã có liên quan. – Krylez

+1

@Krylez đó là tập tin downloding nhưng tôi có một vấn đề mà trong testpdf.php của tôi có chứa tập tin pdf và khi tôi runt url như http://www.tttt.co/testpdf.php tập tin sau đó nó không tải về tập tin pdf nhưng nó tải về testpdf .php tập tin như vậy cany giúp tôi tôi muốn tải về tập tin pdf – CoronaPintu

2
if(mWebview.getUrl().contains(".mp3") { 
Request request = new Request(
         Uri.parse(url)); 
       request.allowScanningByMediaScanner(); 
       request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED); 
       request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "download"); 
// You can change the name of the downloads, by changing "download" to everything you want, such as the mWebview title... 
       DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE); 
       dm.enqueue(request);   

    } 
+0

Cảm ơn rất nhiều nó hoạt động như một nét duyên dáng .. –