我想拦截HTTP请求并从Web应用程序的资产目录加载给定资源。我认为从assets目录加载资源比通过网络加载资源更好。
我想加载像图像,字体,一些HTML的资源,但我很困惑。我使用AssetManager访问了assets目录中的文件。我尝试了一些代码,我的应用程序崩溃了。
我不确定问题是什么。这是我试过的代码:
public class WebViewClientImpl extends WebViewClient {
private Activity activity = null;
public WebViewClientImpl(Activity activity) {
this.activity = activity;
}
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
activity.startActivity(intent);
return true;
}
@Override
public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
if(url.startsWith("http://google.com/images/logo.png")){
return loadFromAssets(url, "images/logo.png", "image/png", "");
}
return null;
}
private WebResourceResponse loadFromAssets( String url,
String assetPath, String mimeType, String encoding){
AssetManager assetManager = this.activity.getAssets();
InputStream input = null;
try {
Log.d(Constants.LOG_TAG, "Loading from assets: " + assetPath);
input = assetManager.open("/images/logo.png");
WebResourceResponse response =
new WebResourceResponse(mimeType, encoding, input);
return response;
} catch (IOException e) {
Log.e("WEB-APP", "Error loading " + assetPath + " from assets: " +
e.getMessage(), e);
}
return null;
}
}