天天看點

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