从 Webview 下载文件在 android 中不起作用,我正在尝试这种方式,

File Download from Webview is not working in android, I am trying this way,

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

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

}

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

我注意到 shouldOverrideUrlLoading 没有被调用。根据 android 文档 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

但在您的情况下,因为 url 在 WebView 地址栏中单击三个链接中的任何一个都没有改变。它只是调用 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.[=20中捕获urls =]

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