无法访问Android中Webview的html文件中存在的url
作者:互联网
我正在尝试使用ShouldOverrideUrlLoading方法访问URL.由于某些原因,当我尝试访问html文件中存在的url时,出现网页不可用错误.以前我可以访问该url,因为我将html文件存储在原始文件夹中,但是我需要将其移至资产中文件夹,因为代码看起来更干净.这是我的代码,谁能让我知道如何解决这个问题.
webview.setWebChromeClient(new WebChromeClient());
webview.setWebViewClient(new WebViewClient());
webview.loadUrl("file:///android_asset/myfile/file.html");
webview.setVerticalScrollBarEnabled(false);
webview.setWebViewClient(new WebViewClient()
{
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (url.equalsIgnoreCase("some text")){
setDialog("some fancy text");
}
解决方法:
尝试先获取文件的真实路径,然后按以下方式尝试:
String YourURI="/android_asset/myfile/file.html";
YourURI = new File(getRealPathFromURI(YourURI));
//Got the Real Path Of the File
private String getRealPathFromURI(Uri contentURI) {
Cursor cursor = getContentResolver().query(contentURI, null, null, null, null);
cursor.moveToFirst();
int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
return cursor.getString(idx);
}
webview.setWebChromeClient(new WebChromeClient());
webview.setWebViewClient(new WebViewClient());
webview.loadUrl(YourURI); //**Used the Real Path**
webview.setVerticalScrollBarEnabled(false);
webview.setWebViewClient(new WebViewClient()
{
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (url.equalsIgnoreCase("some text")){
setDialog("some fancy text");
}
}
如果文件在SDCARD中:
webview.setWebChromeClient(new WebChromeClient());
webview.setWebViewClient(new WebViewClient());
if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED))
{
Log.d(TAG, "No SDCARD");
}
else
{
webview.loadUrl("file://"+Environment.getExternalStorageDirectory()
+"/android_asset/myfile/file.html");
}
webview.setVerticalScrollBarEnabled(false);
webview.setWebViewClient(new WebViewClient()
{
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (url.equalsIgnoreCase("some text")){
setDialog("some fancy text");
}
}
最终编辑:-此代码非常适合资产文件夹
public class MyActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.webview);
WebView webview;
webview = (WebView) findViewById(R.id.webView1);
webview.loadUrl("file:///android_asset/myfile/file.html");
}
}
标签:webview,android-webview,android 来源: https://codeday.me/bug/20191101/1980695.html