Skip to content

Instantly share code, notes, and snippets.

@chethann
Last active September 29, 2020 18:49
Show Gist options
  • Save chethann/3edcc6f702430e42fe4f018546766481 to your computer and use it in GitHub Desktop.
Save chethann/3edcc6f702430e42fe4f018546766481 to your computer and use it in GitHub Desktop.
Sample code of WebResourceResponse to load WebView resources from local assets!
@Override
public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
String resourceUrl = request.getUrl().toString();
String fileExtension = WebviewResourceMappingHelper.getInstance().getFileExt(resourceUrl);
if(WebviewResourceMappingHelper.getInstance().getOverridableExtensions().contains(fileExtension)){
String encoding = "UTF-8";
String assetName = WebviewResourceMappingHelper.getInstance().getLocalAssetPath(resourceUrl);
if (StringUtils.isNotEmpty(assetName)) {
String mimeType = WebviewResourceMappingHelper.getInstance().getMimeType(fileExtension);
if (StringUtils.isNotEmpty(mimeType)) {
try {
Log.e(TAG, assetName);
return WebviewResourceMappingHelper.getWebResourceResponseFromAsset(assetName, mimeType, encoding);
} catch (IOException e) {
return super.shouldInterceptRequest(view, request);
}
}
}
String localFilePath = WebviewResourceMappingHelper.getInstance().getLocalFilePath(resourceUrl);
if (StringUtils.isNotEmpty(localFilePath)) {
String mimeType = WebviewResourceMappingHelper.getInstance().getMimeType(fileExtension);
if(StringUtils.isNotEmpty(mimeType)){
try {
Log.e(TAG, localFilePath);
return WebviewResourceMappingHelper.getWebResourceResponseFromFile(localFilePath, mimeType, encoding);
} catch (FileNotFoundException e) {
return super.shouldInterceptRequest(view,request);
}
}
}
}
if (fileExtension.endsWith("jpg")) {
try {
InputStream inputStream = ImageUtils.readFromCacheSync(resourceUrl);
if (inputStream != null) {
return new WebResourceResponse("image/jpg", "UTF-8", inputStream);
}
} catch (Exception e) {
return super.shouldInterceptRequest(view,request);
}
}
return super.shouldInterceptRequest(view,request);
}
@chethann
Copy link
Author

Yes, this solution is designed to be used inside a hybrid app (some pages in native and some in web)

@lalitgoswami-db
Copy link

please share ImageUtils

@raj050793
Copy link

Hi,
Can you share your Intentservice class where you are hitting json file and syncing resouces

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment