天天看点

h5从android获取资源,Android Webview H5资源本地化

Android Webview H5资源本地化

一. 创建读取资源项目独立模块

1. 项目依赖的好处

符合模块化的思想,他们相互独立。一个项目持有另一个项目的引用,修改更加方便。

(注:compile project编译引用的项目其内容必须包含有java代码、xml布局文件、AndroidManifest等,而且还要在项目的setting.gradle中用include的形式声明引用)

2. 操作步骤导入项目ProjectR

被依赖的项目ProjectR不需要任何改动!

1. 在需要使用的项目中的settings.gradle添加配置

include ‘:ProjectR‘

project(‘:ProjectR‘).projectDir = new File(settingsDir,‘../../ProjectR/‘)

include ‘:ProjectR:app‘

2. 在需要使用的项目中的Module中添加需要引入的library

dependencies {

...

compile project(path: ‘:ProjectR:app‘)

...

}

3. 设置正确的被依赖的项目路径

project(‘:BProject‘).projectDir = new File(settingsDir,‘../../ProjectR/‘)

其中 new File(settingsDir,‘../../ProjectR/‘)参数说明:

参数一: settingsDir 指的是相对于 settings.gradle 文件所在路径

参数二: 填写被依赖项目的路径,**..

public booleaninit(Activity context) {

mainContext=context;return true;

}

publicWebResourceResponse doLoadRes(WebView view, String url) {try{

// 根据url判断是否是需要加载的本地资源进行拦截替换响应资源if (0) {

AssetManager assetManager=mainContext.getAssets();

String locUrl="assets之后的资源路径";

InputStream stream= assetManager.open(locUrl);

WebResourceResponse response= newWebResourceResponse(

MimeTypeMap.getSingleton().getMimeTypeFromExtension(MimeTypeMap.getFileExtensionFromUrl(url))

,"UTF-8", stream

);returnresponse;

}

}catch(FileNotFoundException e) {

}catch(Exception e) {

e.printStackTrace();

}return null;

}

}

二. 主项目代码

1. 将需要本地化的资源放入assets文件夹下。

2. 设置完webview后初始化导入的库:

LocalAssets.getInstance().init(this);

3. 设置webview拦截请求:

@OverridepublicWebResourceResponse shouldInterceptRequest(WebView view, String url) {

WebResourceResponse resp=LocalAssets.getInstance().doLoadRes(view, url);if (resp != null) {returnresp;

}return super.shouldInterceptRequest(view, url);

}

@Override

@RequiresApi(Build.VERSION_CODES.LOLLIPOP)publicWebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {

WebResourceResponse resp=LocaalAssets.getInstance().doLoadRes(view, request.getUrl().toString());if (resp != null) {returnresp;

}return super.shouldInterceptRequest(view, request);

}

原文:https://www.cnblogs.com/dlm17/p/12344302.html