Reputation: 98881
I'm trying to intercept and stop loading all mp4 videos on a webView
, for that I'm using shouldInterceptRequest
. I'm able to intercept the videos and, for ex:, show a dialog but, but I'm not able to stop loading them, any idea why?
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;
}
}
Upvotes: 4
Views: 10121
Reputation: 1
Try this
public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
if (yourCondition) {
webView.post(new Runnable() {
@Override
public void run() {
webView.stopLoading();
}
});
}
return null;
}
Upvotes: 0
Reputation: 7647
If your HTML page does not show mp4 contents or handles invalid content, then you can simply pass some dummy InputStream to WebResourceResponse as shown below.
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)
}
}
}
Upvotes: 3
Reputation: 606
This may help you:
@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);
}
I created the thread because A WebView method ( that is stopLoading() ) can't be called on a currently running thread and that thread is 'Chrome_FileThread'
.
Also, get getMainLooper()
because In above situation we can't create handler inside thread that has not called Looper.prepare()
.
Hope this helps.
Upvotes: 4
Reputation: 2032
The method you want is this one I think
webView.setWebViewClient(new WebViewClient(){
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
// code goes here
}
});
Upvotes: 0