我正在尝试拦截并停止在webView
上加载所有mp4视频,因为我正在使用shouldInterceptRequest
。我能够拦截视频,对于ex:,显示一个对话框,但是,我无法停止加载它们,任何想法为什么?
webView.setWebViewClient(new WebViewClient() {
@SuppressWarnings("deprecation")
@Override
public WebResourceResponse shouldInterceptRequest(final WebView view, String url) {
try {
if (url.contains(".mp4?")) {
return getResponseData();
}
} catch (Exception e) {
e.printStackTrace();
}
return super.shouldInterceptRequest(view, url);
}
private WebResourceResponse getResponseData() {
try {
String str = "Access Denied";
InputStream data = new ByteArrayInputStream(str.getBytes("UTF-8"));
return new WebResourceResponse("text/css", "UTF-8", data);
} catch (IOException e) {
return null;
}
}
答案 0 :(得分:1)
这可能会对您有所帮助:
@Override
public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
if (yourCondition) {
Handler handler = new Handler(getMainLooper());
handler.post(new Runnable() {
@Override
public void run() {
YourwebView.stopLoading();
YourwebView.doAnythingYouWant();
}
});
}
return super.shouldInterceptRequest(view, request);
}
我创建了线程,因为A WebView method ( that is stopLoading() ) can't be called on a currently running thread and that thread is 'Chrome_FileThread'
。
另外,请getMainLooper()
获取In above situation we can't create handler inside thread that has not called Looper.prepare()
。
希望这有帮助。
答案 1 :(得分:0)
如果您的HTML页面不显示mp4内容或处理无效内容,则只需将一些虚拟InputStream传递给WebResourceResponse,如下所示。
my_webview.webViewClient = object : WebViewClient() {
override fun shouldInterceptRequest(view: WebView?, request: WebResourceRequest?): WebResourceResponse? {
if (request?.url?.contains(".mp4") == true) {
val inputStream = "".byteInputStream(Charset.defaultCharset())
return WebResourceResponse("image/png", "UTF-8", inputStream)
} else {
return super.shouldInterceptRequest(view, request)
}
}
}
答案 2 :(得分:-2)
你想要的方法是我想的那个
webView.setWebViewClient(new WebViewClient(){
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
// code goes here
}
});