android - 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.
解决方案
有几件事要做。
- 确保应用具有读取权限并且应用可以访问正确的文件。
- 这是一个很大的安全问题,因此您不应读取公共文件并将其加载到您的应用程序中。
获得文件后,加载其内容。
您还将获得一个URI
ActivityResult。您不能只将 URI 转换为文件。使用它来读取文件的内容。(在科特林)
context.contentResolver.openInputStream(uri).reader().readText()
有了内容后,
webview.loadData(content, MIME_TYPE, ENCODING)
在哪里
MIME_TYPE = "text/html"
ENCODING = "utf-8"
推荐阅读
- hibernate - 休眠和弹簧上的复合ID
- r - 如何将 lowess(或 lm)线添加到现有的 facet_grid
- ocaml - N次函数组合
- json - 使用有效负载的 JSON 液体映射
- javascript - 使用多个函数时如何返回用户输入?
- azure - 限制对特定租户的 Azure Active Directory 应用程序访问
- javascript - 从 Nodejs 获取数据到 html
- asp.net-web-api - Web Api - IIS 10.0 详细错误 - 500.21 - 内部服务器错误
- css - Django CSS没有更新
- odoo - 如何根据采购订单中的字段选择创建一种显示销售订单 ID 的方法?销售订单参考已集成在采购中