从 Webview 下载文件在 android 中不起作用,我正在尝试这种方式, [英] File Download from Webview is not working in android, I am trying this way,

查看:50
本文介绍了从 Webview 下载文件在 android 中不起作用,我正在尝试这种方式,的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面是我实现 webview 的代码,它打开一个链接,其中包含有关日期选择的表格信息底部有三个按钮,用于下载 pdf、xls 和 doc 文件下载在浏览器中运行良好,但在 webview 中没有下载!

public class Reports_Visit_Statastics extends AppCompatActivity {WebView wb;字符串 ReportsURL,标题;@SuppressLint("SetJavaScriptEnabled")@覆盖protected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.visit_statastics_reports);wb = (WebView) findViewById(webView);wb.getSettings().setLoadsImagesAutomatically(true);wb.getSettings().setJavaScriptEnabled(true);wb.setScrollBarStyle(View.SCROLLBARS_OUTSIDE_OVERLAY);捆绑 b = getIntent().getExtras();ReportsURL = b.getString("URL");title = b.getString("title");初始化工具栏();wb.setWebViewClient(new MyWebViewClient());wb.loadUrl(ReportsURL);}私有类 MyWebViewClient 扩展了 WebViewClient {@覆盖public void onReceivedError(WebView view, int errorCode,字符串描述,字符串失败Url) {Log.d("WEB_VIEW_TEST", "错误代码:" + errorCode + " - " + description);}@覆盖public boolean shouldOverrideUrlLoading(WebView view, String url) {//处理不同类型文件的不同请求//此示例处理 .apk 和 .mp3 文件的下载请求//webview 可以正常处理的所有其他内容如果(url.endsWith(.pdf")){uri 源 = uri.parse(url);//发出一个指向 .apk url 的新请求DownloadManager.Request request = new DownloadManager.Request(source);//下载时在通知栏中显示相同request.setDescription("下载管理器栏的说明");request.setTitle("文档");request.allowScanningByMediaScanner();request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);//将文件保存在 SDCARD 的下载"文件夹中request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "Document.doc");//获取下载服务和入队文件DownloadManager manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);manager.enqueue(请求);} else if (url.endsWith(".doc")) {uri 源 = uri.parse(url);//发出一个指向 .apk url 的新请求DownloadManager.Request request = new DownloadManager.Request(source);//下载时在通知栏中显示相同request.setDescription("下载管理器栏的说明");request.setTitle("文档");request.allowScanningByMediaScanner();request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);//将文件保存在 SDCARD 的下载"文件夹中request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "Document.doc");//获取下载服务和入队文件DownloadManager manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);manager.enqueue(请求);} else if (url.endsWith(".xls")) {uri 源 = uri.parse(url);//发出一个指向 .apk url 的新请求DownloadManager.Request request = new DownloadManager.Request(source);//下载时在通知栏中显示相同request.setDescription("下载管理器栏的说明");request.setTitle("文档");request.allowScanningByMediaScanner();request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);//将文件保存在 SDCARD 的下载"文件夹中request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "Document.doc");//获取下载服务和入队文件DownloadManager manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);manager.enqueue(请求);}//如果有一个指向除 .apk 或 .mp3 之外的任何内容的链接,则在 webview 中加载 URL否则 view.loadUrl(url);返回真;}}私人无效initToolbar(){最终工具栏工具栏 = (工具栏) findViewById(R.id.toolbar);setSupportActionBar(工具栏);最终 ActionBar actionBar = getSupportActionBar();尝试 {如果(动作条!= null){actionBar.setTitle(title);actionBar.setHomeButtonEnabled(true);actionBar.setDisplayHomeAsUpEnabled(true);}} 捕获(异常 e){Log.d("Doctor_master", e.toString());}}@覆盖公共无效 onBackPressed() {super.onBackPressed();}@覆盖公共布尔 onOptionsItemSelected(MenuItem item) {int id = item.getItemId();如果(id == android.R.id.home){onBackPressed();返回真;}返回 super.onOptionsItemSelected(item);}}

解决方案

基于聊天中的评论和讨论.

我注意到 shouldOverrideUrlLoading 没有被调用.正如,根据 android 文档 shouldOverrideUrlLoading

<块引用>

当新的应用程序出现时,给宿主应用程序一个接管控制权的机会url 即将加载到当前 WebView

但在您的情况下,因为在单击三个链接中的任何一个时 WebView 地址栏中的 url 不会更改.它只是调用javascript代码javascript:__doPostBack('lnkPDF',''),它调用post方法来生成文件.如果你想使用 DownloadManager 在通知区域显示通知的同时下载文件,你需要为 http://或 https://等文件创建动态静态 url.例如.http://www.somedomain/may_be_session_id/some_random_file_number_valid_for_some_time_only/file_name.pdf.>

除上述之外,让网页改变或重定向到新的url,只有这样你才能在shouldOverrideUrlLoading中捕获url.

如果宿主应用程序想要离开当前的 WebView 并自行处理 url,请尝试将 shouldOverrideUrlLoading 中的 return 实现更改为 True,否则返回 false.

Below is my Code for implementing a webview which opens a link which have tabular information on date selection and having three buttons in the bottom for downloading pdf, xls and doc file download works well in browser but in webview download is not happening!

public class Reports_Visit_Statastics extends AppCompatActivity {

WebView wb;
String ReportsURL, title;
@SuppressLint("SetJavaScriptEnabled")
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.visit_statastics_reports);
    wb = (WebView) findViewById(webView);
    wb.getSettings().setLoadsImagesAutomatically(true);
    wb.getSettings().setJavaScriptEnabled(true);
    wb.setScrollBarStyle(View.SCROLLBARS_OUTSIDE_OVERLAY);
    Bundle b = getIntent().getExtras();
    ReportsURL = b.getString("URL");
    title = b.getString("title");
    initToolbar();
    wb.setWebViewClient(new MyWebViewClient());
    wb.loadUrl(ReportsURL);

}

private class MyWebViewClient extends 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(".pdf")) {
            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("Document");

                request.allowScanningByMediaScanner();
                request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);

            // save the file in the "Downloads" folder of SDCARD
            request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "Document.doc");
            // get download service and enqueue file
            DownloadManager manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
            manager.enqueue(request);
        } else if (url.endsWith(".doc")) {
            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("Document");

                request.allowScanningByMediaScanner();
                request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);

            // save the file in the "Downloads" folder of SDCARD
            request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "Document.doc");
            // get download service and enqueue file
            DownloadManager manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
            manager.enqueue(request);
        } else if (url.endsWith(".xls")) {
            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("Document");

                request.allowScanningByMediaScanner();
                request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);

            // save the file in the "Downloads" folder of SDCARD
            request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "Document.doc");
            // get download service and enqueue file
            DownloadManager manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
            manager.enqueue(request);
        }
        // if there is a link to anything else than .apk or .mp3 load the URL in the webview
        else view.loadUrl(url);
        return true;
    }
}


private void initToolbar() {

    final Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    final ActionBar actionBar = getSupportActionBar();

    try {
        if (actionBar != null) {
            actionBar.setTitle(title);
            actionBar.setHomeButtonEnabled(true);
            actionBar.setDisplayHomeAsUpEnabled(true);
        }
    } catch (Exception e) {
        Log.d("Doctor_master", e.toString());
    }
}



@Override

public void onBackPressed() {

    super.onBackPressed();
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    int id = item.getItemId();

    if (id == android.R.id.home) {
        onBackPressed();
        return true;
    }
    return super.onOptionsItemSelected(item);
}

}

解决方案

Based on the comments and discussion from the chat.

I have noticed that shouldOverrideUrlLoading is not being called. As, per the android documentation shouldOverrideUrlLoading

Give the host application a chance to take over the control when a new url is about to be loaded in the current WebView

But in your case since url doesn't change in WebView address bar while clicking any of the three links. It just call javascript code javascript:__doPostBack('lnkPDF',''), which calls the post method to generate the file. If you to want use DownloadManager to download file while showing notification in notification area, you need to create dynamic static url for files like http:// or https://. E.g. http://www.somedomain/may_be_session_id/some_random_file_number_valid_for_some_time_only/file_name.pdf.

In addition to the above, let the web page change or redirect to new url, only then you will be able to capture urls in shouldOverrideUrlLoading.

Try changing your implementation of return in shouldOverrideUrlLoading to True if the host application wants to leave the current WebView and handle the url itself, otherwise return false.

这篇关于从 Webview 下载文件在 android 中不起作用,我正在尝试这种方式,的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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