我正在尝试使用shouldInterceptRequest来关闭我的webview,当我想加载某些URL但是当我这样做时应用程序崩溃。
要检查来自网络的内容的网址,请使用webview.getURL()方法。我在UI线程上运行此方法以获取URL。
请在下面找到我的代码
public WebResourceResponse shouldInterceptRequest(final WebView view, String url) {
WebActivity.this.runOnUiThread(new Runnable() {
@Override
public void run() {
CloseURL = webView.getUrl();
}
});
if (CloseURL.contains("dummyurl") &&BackPressed) {
BackPressed=false;
CloseURL="";
WebActivity.this.finish();
}
return super.shouldInterceptRequest(view, url);
}
答案 0 :(得分:1)
When you do this,
WebActivity.this.runOnUiThread(new Runnable() {
@Override
public void run() {
CloseURL = webView.getUrl();
}
});
it queues that code to run later. Then you go on to use CloseUrl
immediately after this. If you are expecting CloseUrl
to be assigned when you use it here,
if (CloseURL.contains("dummyurl") &&BackPressed) {
you are wrong, it won't have been assigned yet. The code that assigns it won't have run yet.
You should move the code that depends on CloseUrl
into your Runnable.run()
.
public WebResourceResponse shouldInterceptRequest(final WebView view, String url) {
WebActivity.this.runOnUiThread(new Runnable() {
@Override
public void run() {
CloseURL = webView.getUrl();
if (CloseURL.contains("dummyurl") &&BackPressed) {
BackPressed=false;
CloseURL="";
WebActivity.this.finish();
}
}
});
return super.shouldInterceptRequest(view, url);
}