如何从Android WebView中的远程URL访问本地资产? [英] How to access local assets from a remote URL in Android WebView?

查看:423
本文介绍了如何从Android WebView中的远程URL访问本地资产?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

要使用HTML加载资产,我正在使用URL file:///android_asset/my_image.png. 当我在本地加载HTML时,例如使用WebView.loadData()方法,它就可以工作.

To load an asset in HTML, I am using the URL file:///android_asset/my_image.png. It works when I am loading HTML locally, for instance, using a WebView.loadData() method.

但是,例如,当我使用WebView.loadUrl("http://example.com/my_page.html")加载页面时,无法从远程网站加载本地资产.它显示了页面,但未加载图像.

However, I am unable to load a local asset from a remote web site, for instance, when I load a page using WebView.loadUrl("http://example.com/my_page.html"). It shows the page, but the image is not loaded.

如何解决此问题?

更新:

tarkeshwar提到由于安全原因,这是不可能的.我了解您在浏览器中打开网页时,那么您作为用户将无法控制该网页正在访问什么.当您读取用户的敏感数据时,访问本地文件系统也有些不同.在这里,我只想访问应用程序资产.

tarkeshwar mentioned that it is not possible because of security reasons. I understand when you open a web page in a browser, then you as a user are unable to control what the web page is accessing. And it is also a bit different to access local file system when you may read sensitive data of the user. Here I would like just to access application assets.

一种解决方法是,使用loadData()方法下载页面并将其加载到WebView中.但是可能会有一些安全开关允许WebView访问本地资产.

A workaround could be, to download the page and load it into the WebView using loadData() method. But there might be some security switch to allow WebView to access local assets.

UPDATE2: 我需要支持Android 2.3 +.

UPDATE2: I need to support Android 2.3+.

推荐答案

扩展WebViewClient并覆盖shouldInterceptRequest以在本地加载文件.这些网址都将显示在远程位置,但是您可以有选择地加载所有需要的网址.

Extend WebViewClient and override shouldInterceptRequest to load the file locally. The urls would all appear remote but you can selectively load which every you need.

http://developer.android .com/reference/android/webkit/WebViewClient.html#shouldInterceptRequest(android.webkit.WebView ,java.lang.String)

http://developer.android.com/reference/android/webkit/WebViewClient.html#shouldInterceptRequest(android.webkit.WebView, java.lang.String)

也在这里回答: webview应interceptrequest示例

这篇关于如何从Android WebView中的远程URL访问本地资产?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆