I got to a dead loop in Android webview application with backkey while dealing with redirect links.
For example, when my webview started, it goes to link0.
In l
Annoying redirects get into the backforward history. Detect when url loading is triggered by the user, and add those to the backstack instead.
private List<String> previous = new ArrayList<String>();
private String mLastUrl;
webview.setWebViewClient(new WebViewClient() {
@Override
public void onPageFinished(WebView view, String url) {
Log.i("DebugDebug", "OnPageFinished " + url);
mLastUrl = url;
super.onPageFinished(view, url);
}
});
webview.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View view, MotionEvent motionEvent) {
WebView.HitTestResult hr = ((WebView)view).getHitTestResult();
if (hr != null && mLastUrl != null) {
if (previous.isEmpty() || !previous.get(previous.size() - 1).equals(mLastUrl)) {
previous.add(mLastUrl);
}
Log.i("DebugDebug", "getExtra = " + hr.getExtra() + "\t\t Type = " + hr.getType());
}
return false;
}
});
@Override
public void onBackPressed() {
Log.i("DebugDebug", "onBackPressed");
int size = previous.size();
if (size > 0){
webview.loadUrl(previous.get(size - 1));
previous.remove(size - 1);
} else {
super.onBackPressed();
}
}
I had a same problem and solved it. Here is my answer.
When I click the first link(www.new.a) it automatically redirects other link(mobile.new.a). Usually the links redirect two or three, and my solution have been worked on almost every redirect links. I hope this answer help you out with annyoing redirecting links.
I finally figured out that. You need a WebViewClient with four APIs. There are shouldOverrideUrlLoading(), onPageStarted(), onPageFinished(), and doUpdateVisitedHistory() in the WebViewClient. All the APIs you need is API 1 so don't worry about.
Here is my answer. Check out that! :)
webview.setWebViewClient(new WebViewClient(){
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
Log.i(tag, "url = " + url);
// view.loadUrl(url);
// return super.shouldOverrideUrlLoading(view, url);
return false;
}
});
look!!!! the important, shouldOverrideUrlLoading must return false
in shouldOverrideUrlLoading you can't invoke view.loadUrl.
shouldOverrideUrlLoading()
is called on a per-URL basis. So, if http://site1.com/ redirects to http://site2.com/, which then redirects to http://site3.com/, you are calling WebView.loadUrl()
for each of these URL's. Thus each appears in the back stack.
Instead of creating a WebViewClient
you probably want a WebChromeClient
. WebChromeClient
defines a method onCreateWindow
that is only invoked when the WebView
is trying to create a new window, not for every single URL it accesses.