Dead loop in android webview backkey for redirect href link

Viewed 5181

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 link0, there is a href link which link to link1. Link1 redrect to link2.

So if I click link1, it will go to link1, then redirect to link2. When I click backkey, it should go back to link0, in my case. But instead, it goes to link1, which redirect back to link2 again. So I never have a chance to go back.

The backkey works correctly with other links if they are not redirect links.

I googled webs for help, but didn't find related question.

By the way, the backkey works in the internet browser as expected. But not in webview.

Below is my code, for you to try. As you can see in the code, I tried both onBackPressed and onKeyDown, but neigher works.

Thanks for your kind help. I have struglling on this for a while.

==================================================================================

public class MyActivity extends Activity 
{
    private WebView myWebView;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        myWebView = (WebView) findViewById(R.id.webview);
        myWebView.getSettings().setJavaScriptEnabled(true);
        myWebView.loadUrl("http://50.112.242.120/temp/");
        myWebView.setWebViewClient(new MyWebViewClient());
    }

    private class MyWebViewClient extends WebViewClient {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            myWebView.loadUrl(url);
            return true;
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        // Check if the key event was the Back button and if there's history
        if ((keyCode == KeyEvent.KEYCODE_BACK) && myWebView.canGoBack()) {
            myWebView.goBack();
            return true;
        }
        // If it wasn't the Back key or there's no web page history, bubble up to the default
        // system behavior (probably exit the activity)
        return super.onKeyDown(keyCode, event);
    }
}

.

// main.xml
<?xml version="1.0" encoding="utf-8"?>
<WebView  xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/webview"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
/>
4 Answers
Related