WebView 未从内部存储加载文件

WebView not loading the file from internal storage

我正在尝试从服务器下载 HTML 文件,然后将其加载到网络视图中。正在下载文件,但未在 web 视图中加载。即使在下载完成后重新启动应用程序后,Webview 也会显示 net::ERR_FILE_NOT_FOUND

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    webView = (WebView) findViewById(R.id.webView);
    button = (Button) findViewById(R.id.button);
    webView.loadUrl("file://"+Environment.DIRECTORY_DOWNLOADS+File.separator+"test.html");
    Log.e("CHECKKK", String.valueOf(Environment.DIRECTORY_DOWNLOADS+File.separator+"test.html"));

    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            try {
                myDownload("http://xxxxxx.com/xxxx/test.html");
                myDownload("http://xxxxxx.com/xxxx/mypic1.jpg");
            } catch (Exception e) {
                Toast.makeText(MainActivity.this, e.getMessage() + "\n" + e.getCause(), Toast.LENGTH_LONG).show();
            }
        }
    });
}

public void myDownload(String myURL) {

    DownloadManager.Request request = new DownloadManager.Request(Uri.parse(myURL));
    request.setTitle("File Download");
    request.setDescription("Downloading....");
    request.allowScanningByMediaScanner();
    request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
    String nameOfFile = URLUtil.guessFileName(myURL, null, MimeTypeMap.getFileExtensionFromUrl(myURL));
    request.setDestinationInExternalFilesDir(this,Environment.DIRECTORY_DOWNLOADS, nameOfFile);

    DownloadManager manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
    manager.enqueue(request);
}

将文件读入String然后使用

// read from file
String summary = "<html><body>You scored <b>192</b> points.</body></html>";
webview.loadData(summary, "text/html", null);

调用 webView.loadUrl() 应该可以,但我认为您的文件路径字符串中缺少斜线。你可以试试 "file:///"+Environment.DIRECTORY_DOWNLOADS+File.separator+"test.html"

注意 file:///

中的额外斜线

您也可能没有正确访问下载文件夹。尝试这样做:

File file = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
File htmlFile = new File(file.getAbsolutePath()+"/test.html");
webView.loadUrl(htmlFile.getAbsolutePath());

更新

似乎需要混合使用其中一些方法。正确的格式是: webView.loadUrl("file://"+htmlFile.getAbsolutePath());