webview html中加载本地图片,008.WebView加载本地js图片的方式

Android中混合式开发的过程中,加载html页面的时候,如果该页面加载的资源比较多,比如css,js,公用的图片资源等,就会导致该页面加载缓慢,耗费大量的流量,这对流量限制的客户端来说,用户体验非常不好,所以就需要将这些资源存放在APP中,待APP启动的时候,直接从本地加载这些公用的资源。(本方法只针对html文件从网络上获取)

方式一:使用loadDataBaseUrl的方式

当从网络上加载的html页面中包含“file:///……”或者“content://packagename/……”(content://……这种需要重写Provider)这样的路径时,可以直接使用loadDataWithBaseURL("file:///",htmlSource,"text/html;charset=utf-8",null,null)重新加载,其中htmlSource为网页源代码。

参考"stackoverflow" Load HTML data into WebView, referencing local images?

activity中示例代码

/**

* 加载html文件

* @param path 文件路径

*/

private void loadHtml(final String path){

new Thread(new Runnable() {

@Override

public void run() {

try {

URL url = new URL(path.trim());

HttpURLConnection conn = (HttpURLConnection) url.openConnection();

conn.setDoInput(true); //允许输入流,即允许下载

conn.setDoOutput(true); //允许输出流,即允许上传

conn.setUseCaches(false); //不使用缓冲

conn.setRequestMethod("GET"); //使用get请求

if (conn.getResponseCode() == 200){

InputStream inputStream = conn.getInputStream();

ByteArrayOutputStream baos = new ByteArrayOutputStream();

byte[] buffer = new byte[1024];

int length = -1;

while((length = inputStream.read(buffer))!=-1){

baos.write(buffer,0,length);

baos.flush();

}

final String htmlSource = baos.toString();

runOnUiThread(new Runnable(){

@Override

public void run() {

//重写

mWebView.loadDataWithBaseURL("file:///",htmlSource,"text/html;charset=utf-8",null,null);

}

});

}

} catch (Exception e) {

e.printStackTrace();

}

}

}).start();

}

H5示例代码(该h5页面是放在服务器上面的)

H5调用Native“获取地理位置”与“拍照上传“的功能
H5调用安卓“拍照上传“的功能:

css文件内容如下

.text-left{background-color:#f00}

236c3ba7c61e

IMG_20161214_163615.jpg

正常结果如上所示。

方式二:使用ContentProvider的方式

使用content://方式访问本地资源的时候,需要重写ContentProvider,简单代码如下:

public class LoadPicProvider extends ContentProvider {

@Override

public boolean onCreate() {

return false;

}

@Nullable

@Override

public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {

return null;

}

@Nullable

@Override

public String getType(Uri uri) {

return null;

}

@Nullable

@Override

public Uri insert(Uri uri, ContentValues values) {

return null;

}

@Override

public int delete(Uri uri, String selection, String[] selectionArgs) {

return 0;

}

@Override

public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {

return 0;

}

@Nullable

@Override

public ParcelFileDescriptor openFile(Uri uri, String mode) throws FileNotFoundException {

URI filePath = URI.create( "file://" + uri.getPath() );

File file = new File( filePath );

ParcelFileDescriptor parcel = null;

try {

parcel = ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY);

} catch (FileNotFoundException e) {

e.printStackTrace();

}

return parcel;

}

}

然后在mainfest中进行注册

方式三:使用Base64的方式

ByteArrayOutputStream out = new ByteArrayOutputStream();

//TODO 文件读取需要线程操作

FileInputStream fis = new FileInputStream(imageCropUri.toString());

byte buff[] = new byte[1024];

int length = -1;

while((length = fis.read(buff))!= -1){

out.write(buff,0,length);

out.flush();

}

String fileBase64 = Base64.encodeToString(out.toByteArray(),Base64.NO_WRAP);

//将当前的fileBase64传到h5页面中,并设置到img上

js代码

方式四:使用shouldInterceptRequest进行文件资源的拦截

从API 11(Android 3.0)开始引入这个方法。shouldInterceptRequest这个回调可以通知主程序WebView处理的资源(css,js,image等)请求,并允许主程序进行处理后返回数据。如果主程序返回的数据为null,WebView会自行请求网络加载资源,否则使用主程序提供的数据。注意这个回调发生在非UI线程中,所以进行UI系统相关的操作是不可以的。

shouldInterceptRequest有两种重载。

public WebResourceResponse shouldInterceptRequest (WebView view, String url) 从API 11开始引入,API 21弃用

public WebResourceResponse shouldInterceptRequest (WebView view, WebResourceRequest request) 从API 21开始引入

所以在使用的时候,最好两者都要进行重写。

测试代码如下

mWebView.setWebViewClient(new WebViewClient() {

@Override

public WebResourceResponse shouldInterceptRequest(WebView view, String url) {

String key = "http://localhost/";

WebResourceResponse response = null;

if (url.contains(key)) {

try {

String imgPath = url.replace(key,"");

imgPath = Uri.parse(imgPath).getPath();

InputStream localCopy = new FileInputStream(imgPath);

//当前只针对图片

response = new WebResourceResponse("image/png", "UTF-8", localCopy);

} catch (IOException e) {

e.printStackTrace();

}

}

return response;

}

});

注意:当从本地相册拍照完成后,图片的uri可能是这样的file:///storage/emulated/0/newCrop.jpg,如果这个url回调给 js是显示不出来的。因为webview根本不会自动加载。所以这个时候可以考虑在当前地址上面添加http://……这样这个url设置完成之后,才能够正常的发出。

例如我得拍照产生的image的uri如下

用拦截的方式显示不出来,然后后我改为

这样在http请求发生的时候,会被shouldInterceptRequest方法拦截

参看链接:

Webview加载本地图片的方案对比

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值