如何下载从web视图Android的文件吗? [英] How to download files from webview Android?

查看:85
本文介绍了如何下载从web视图Android的文件吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面负荷的URL页面精美,寻找,当我点击它崩溃的下载链接一首歌曲后,我的code。有没有那么多的教程如何让下载管理器与一个web视图的工作。我究竟做错了什么?

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


公共类的List1延伸活动{

        的WebView ourBrow;


    @覆盖
    公共无效的onCreate(包savedInstanceState){
        super.onCreate(savedInstanceState);

        //使用自定义布局文件
        的setContentView(R.layout.list1);

        最终的下载管理器管理器=(下载管理器)getSystemService(Context.DOWNLOAD_SERVICE);

     最终文件destinationDir =新的文件(Environment.getExternalStorageDirectory(),getPackageName());
     如果(!destinationDir.exists()){
         destinationDir.mkdir(); //不要忘了做目录,如果它不存在
     }

        ourBrow =(web视图)findViewById(R.id.wvBrowser);
        ourBrow.getSettings()setJavaScriptEnabled(真)。
        ourBrow.setInitialScale(50);
        。ourBrow.getSettings()setUseWideViewPort(真正的);
        ourBrow.setVerticalScrollBarEnabled(假);
        ourBrow.setHorizo​​ntalScrollBarEnabled(假);
        ourBrow.loadUrl(http://www.degjo.com);



        ourBrow.setWebViewClient(新WebViewClient(){
            @覆盖
            公共布尔shouldOverrideUrlLoading(web视图查看,字符串URL){
                布尔shouldOverride = FALSE;
                //我们只希望来处理MP3文件的请求,一切的web视图
                //可以处理正常
                如果(url.endsWith(。MP3)){
                    shouldOverride = TRUE;
                    乌里源= Uri.parse(URL);

                    //创建一个新的请求指向MP3网址
                    DownloadManager.Request请求=新DownloadManager.Request(源);
                    //使用相同的文件名的目标
                    文件destinationFile =新的文件(destinationDir,source.getLastPathSegment());
                    request.setDestinationUri(Uri.fromFile(destinationFile));
                    //添加到经理
                    manager.enqueue(要求);
                }
                返回shouldOverride;
            }
        });





    }
}
 

LogCat中

  02-18 19:45:44.891:E / AndroidRuntime(357):在android.content.ContentProviderProxy.insert(ContentProviderNative.java:408)
02-18 19:45:44.891:E / AndroidRuntime(357):在android.content.ContentResolver.insert(ContentResolver.java:604)
02-18 19:45:44.891:E / AndroidRuntime(357):在android.app.DownloadManager.enqueue(DownloadManager.java:750)
02-18 19:45:44.891:E / AndroidRuntime(357):在com.example.androidbuttonsactivities.List1 $ 1.shouldOverrideUrlLoading(List1.java:78)
02-18 19:45:44.891:E / AndroidRuntime(357):在android.webkit.CallbackProxy.uiOverrideUrlLoading(CallbackProxy.java:216)
02-18 19:45:44.891:E / AndroidRuntime(357):在android.webkit.CallbackProxy.handleMessage(CallbackProxy.java:323)
02-18 19:45:44.891:E / AndroidRuntime(357):在android.os.Handler.dispatchMessage(Handler.java:99)
02-18 19:45:44.891:E / AndroidRuntime(357):在android.os.Looper.loop(Looper.java:123)
02-18 19:45:44.891:E / AndroidRuntime(357):在android.app.ActivityThread.main(ActivityThread.java:3683)
02-18 19:45:44.891:E / AndroidRuntime(357):在java.lang.reflect.Method.invokeNative(本机方法)
02-18 19:45:44.891:E / AndroidRuntime(357):在java.lang.reflect.Method.invoke(Method.java:507)
02-18 19:45:44.891:E / AndroidRuntime(357):在com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:839)
02-18 19:45:44.891:E / AndroidRuntime(357):在com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
02-18 19:45:44.891:E / AndroidRuntime(357):在dalvik.system.NativeStart.main(本机方法)
02-18 19:45:48.401:I /处理(357):发送信号。 PID:357 SIG:9
 

解决方案

这可能是依赖于Android编译版本的问题,下面的code将成功地工作在2.3+版本中,检查了这一点,

  ourBrow.setWebViewClient(新WebViewClient(){
        @覆盖
        公共无效onReceivedError(web视图来看,INT错误code,
            字符串描述,字符串failingUrl){
                Log.d(WEB_VIEW_TEST,错误code:+错误code + - +说明);
        }

        @覆盖
        公共布尔shouldOverrideUrlLoading(web视图查看,字符串URL){
                //处理针对不同类型的文件不同的要求
                //这个例子处理的.apk文件和.mp3文件下载请求
                //一切web视图可以处理正常
                如果(url.endsWith(。APK)){
                    乌里源= Uri.parse(URL);
                    //创建一个新的请求指向.apk文件网址
                    DownloadManager.Request请求=新DownloadManager.Request(源);
                    //下载时会出现在通知栏相同
                    request.setDescription(描述的下载管理器栏);
                    request.setTitle(YourApp.apk);
                    如果(Build.VERSION.SDK_INT> = Build.VERSION_ codeS.HONEYCOMB){
                        request.allowScanningByMediaScanner();
                        request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
                    }
                    //文件保存在SD卡中的下载文件夹
                    request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADSSmartPigs.apk);
                    //获取下载服务和排队文件
                    下载管理经理=(下载管理器)getSystemService(Context.DOWNLOAD_SERVICE);
                    manager.enqueue(要求);
                }
                否则,如果(url.endsWith(MP3)){
                    //如果该链接指向一个MP3播放资源做其他事
                }
                //如果有一个链接到任何东西比.apk文件或MP3播放加载的URL的web视图
                其他view.loadUrl(URL);
                返回true;
        }
    });
 

My code below loads the url page fine and after searching for a song when I click on the download link it crashes. There aren't so much tutorials on how to get the download manager to work with a webview. What am I doing wrong?

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

解决方案

It may be depends on the android build version problem, the below code will work successfully on 2.3+ builds, check this out,

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

这篇关于如何下载从web视图Android的文件吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆