如何从Webview Android下载文件?

德里坦·伯恩(Dritan Berne)

我下面的代码可以很好地加载url页面,当我单击下载链接搜索歌曲后,它崩溃了。没有太多关于如何使下载管理器与Webview一起使用的教程。我究竟做错了什么?

import java.io.File;
import android.app.Activity;
import android.app.DownloadManager;
import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.webkit.WebView;
import android.webkit.WebViewClient;


public class List1 extends Activity {

        WebView ourBrow;


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // Use a custom layout file
        setContentView(R.layout.list1);

        final DownloadManager manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);

     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
     }

        ourBrow = (WebView) findViewById(R.id.wvBrowser);
        ourBrow.getSettings().setJavaScriptEnabled(true);
        ourBrow.setInitialScale(50); 
        ourBrow.getSettings().setUseWideViewPort(true); 
        ourBrow.setVerticalScrollBarEnabled(false);
        ourBrow.setHorizontalScrollBarEnabled(false);
        ourBrow.loadUrl("http://www.degjo.com");



        ourBrow.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;
            }
        });





    }
}

LogCat

02-18 19:45:44.891: E/AndroidRuntime(357):  at android.content.ContentProviderProxy.insert(ContentProviderNative.java:408)
02-18 19:45:44.891: E/AndroidRuntime(357):  at android.content.ContentResolver.insert(ContentResolver.java:604)
02-18 19:45:44.891: E/AndroidRuntime(357):  at android.app.DownloadManager.enqueue(DownloadManager.java:750)
02-18 19:45:44.891: E/AndroidRuntime(357):  at com.example.androidbuttonsactivities.List1$1.shouldOverrideUrlLoading(List1.java:78)
02-18 19:45:44.891: E/AndroidRuntime(357):  at android.webkit.CallbackProxy.uiOverrideUrlLoading(CallbackProxy.java:216)
02-18 19:45:44.891: E/AndroidRuntime(357):  at android.webkit.CallbackProxy.handleMessage(CallbackProxy.java:323)
02-18 19:45:44.891: E/AndroidRuntime(357):  at android.os.Handler.dispatchMessage(Handler.java:99)
02-18 19:45:44.891: E/AndroidRuntime(357):  at android.os.Looper.loop(Looper.java:123)
02-18 19:45:44.891: E/AndroidRuntime(357):  at android.app.ActivityThread.main(ActivityThread.java:3683)
02-18 19:45:44.891: E/AndroidRuntime(357):  at java.lang.reflect.Method.invokeNative(Native Method)
02-18 19:45:44.891: E/AndroidRuntime(357):  at java.lang.reflect.Method.invoke(Method.java:507)
02-18 19:45:44.891: E/AndroidRuntime(357):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
02-18 19:45:44.891: E/AndroidRuntime(357):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
02-18 19:45:44.891: E/AndroidRuntime(357):  at dalvik.system.NativeStart.main(Native Method)
02-18 19:45:48.401: I/Process(357): Sending signal. PID: 357 SIG: 9
布伦登

可能取决于android build版本的问题,以下代码将在2.3+版本上成功运行,请检查一下,

ourBrow.setWebViewClient(new WebViewClient() {
        @Override
        public void onReceivedError(WebView view, int errorCode,
            String description, String failingUrl) {
                Log.d("WEB_VIEW_TEST", "error code:" + errorCode + " - " + description);
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
                // handle different requests for different type of files
                // this example handles downloads requests for .apk and .mp3 files
                // everything else the webview can handle normally
                if (url.endsWith(".apk")) {
                    Uri source = Uri.parse(url);
                    // Make a new request pointing to the .apk url
                    DownloadManager.Request request = new DownloadManager.Request(source);
                    // appears the same in Notification bar while downloading
                    request.setDescription("Description for the DownloadManager Bar");
                    request.setTitle("YourApp.apk");
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
                        request.allowScanningByMediaScanner();
                        request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
                    }
                    // save the file in the "Downloads" folder of SDCARD
                    request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "SmartPigs.apk");
                    // get download service and enqueue file
                    DownloadManager manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
                    manager.enqueue(request);
                }
                else if(url.endsWith(".mp3")) {
                    // if the link points to an .mp3 resource do something else
                }
                // if there is a link to anything else than .apk or .mp3 load the URL in the webview
                else view.loadUrl(url);
                return true;                
        }
    });

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章

来自分类Dev

如何从Heroku bash下载文件?

来自分类Dev

如何使用restsharp下载文件

来自分类Dev

如何使用硒下载文件?

来自分类Dev

如何下载文件

来自分类Dev

如何在Watir中下载文件?

来自分类Dev

如何从http url下载文件?

来自分类Dev

如何从Google Blobstore下载文件到android

来自分类Dev

如何从HTTPResponseMessage下载文件

来自分类Dev

如何安全下载文件

来自分类Dev

如何快速下载文件?

来自分类Dev

在Android Webview中下载文件

来自分类Dev

如何从git仓库下载文件?

来自分类Dev

Android Webview:像浏览器一样下载文件

来自分类Dev

如何使用C从http下载文件?

来自分类Dev

如何在webView中下载文件?

来自分类Dev

Firebase Storage Android:如何更改下载文件的文件名?

来自分类Dev

从WebView下载文件返回HTML内容而不是实际文件

来自分类Dev

使用Android Webview下载文件

来自分类Dev

如何从gridview下载文件?

来自分类Dev

如何从Google Blobstore下载文件到Android

来自分类Dev

如何在Android中下载文件

来自分类Dev

如何让人们下载文件

来自分类Dev

如何点击下载文件

来自分类Dev

如何在webView中下载文件?

来自分类Dev

Firebase Storage Android:如何更改下载文件的文件名?

来自分类Dev

带有 webview 的 Android 下载文件

来自分类Dev

Android Webview 不触发 href 下载文件

来自分类Dev

如何允许在 Webview 中下载文件?

来自分类Dev

如何下载文件?