首页 > 解决方案 > How to Load html file in to WebView from Device storage downloads folder

问题描述

My HTML file is a game file contains sounds images animations, I am able to retrieve the file but it is not playing. I know how to access it from project asset folder using:

myWebView.loadUrl("file:///android_asset/____/index.html");

but when I receive it from device storage from Download folder I'm unable to play the file in webview.

Below is the code to show up html files from Download folder :

Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
Uri uri = Uri.parse(Environment.getExternalStorageDirectory().getPath() + "/Download");
intent.setDataAndType(uri, "text/html");
startActivityForResult(intent,PICKFILE_RESULT_CODE); 

and in the onActivityResult I wrote like this :

@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    switch (requestCode){
        case PICKFILE_RESULT_CODE :
            if(resultCode==RESULT_OK){
                Uri uri1 = data.getData();
                File file1 = new File(uri1.getPath());
                final String[] split = file1.getPath().split(":");

                String filePath = split[1];

               /* after splitting it will be /storage/emulated/0/Download/index.html */

                if (filePath.endsWith(".html")){
                    mywebview.setWebContentsDebuggingEnabled(true);
                    mywebview.getSettings().setJavaScriptEnabled(true);
                    mywebview.getSettings().setBuiltInZoomControls(true);
                    mywebview.getSettings().setUseWideViewPort(true);
                    mywebview.getSettings().setAllowUniversalAccessFromFileURLs(true);
                    mywebview.getSettings().setAllowFileAccessFromFileURLs(true);
                    mywebview.clearCache(true);
                    mywebview.setWebViewClient(new WebViewClientClass());
                    mywebview.loadUrl(filePath);
                    mywebview.evaluateJavascript(filePath);
                }

            }
            break;
    }
}

private class WebViewClientClass extends WebViewClient {
    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        view.loadUrl(url);
        return true;
    }
}

So please correct me if I am doing anything wrong or tell me the correct way.

标签: androidhtmlandroid-studioandroid-intentandroid-webview

解决方案


有几件事要做。

  1. 确保应用具有读取权限并且应用可以访问正确的文件。
  2. 这是一个很大的安全问题,因此您不应读取公共文件并将其加载到您的应用程序中。

获得文件后,加载其内容。

您还将获得一个URIActivityResult。您不能只将 URI 转换为文件。使用它来读取文件的内容。(在科特林)

context.contentResolver.openInputStream(uri).reader().readText()

有了内容后,

webview.loadData(content, MIME_TYPE, ENCODING)

在哪里

MIME_TYPE = "text/html"
ENCODING = "utf-8"

推荐阅读