如何加载您在webview中打开的最后一个URL

时间:2015-06-20 14:50:10

标签: android webview

我有:

package my.domain.app;    

import android.app.Activity;
import android.os.Bundle;
import android.content.SharedPreferences;
import android.webkit.*;



public class MainActivity extends Activity {
    private WebView webView;
    private SharedPreferences sPref;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.webapp);
    }

    void someMethod() {
        WebView webView = (WebView) findViewById(R.id.webView);
        webView.setWebViewClient(new MyWebViewClient());

        String url;

        if (sPref.contains("PREFS_ID"))
            url = sPref.getString("PREFS_ID", "DEFAULT_VALUE");
        else
            url = "http://example.com";

        WebSettings webSettings = webView.getSettings();
        webSettings.setJavaScriptEnabled(true);
        webSettings.setBuiltInZoomControls(true);
        webSettings.setAllowContentAccess(true);
        webSettings.setSupportZoom(true);
        webSettings.setRenderPriority(WebSettings.RenderPriority.HIGH);

        MyWebViewClient myWebViewClient = new MyWebViewClient();
        webView.setWebViewClient(myWebViewClient);
        webView.loadUrl(url);
    }

    private class MyWebViewClient extends WebViewClient {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            if (!url.equals("YOUR_FIRSTURL")) {
                sPref.edit().putString(url, "PREFS_ID").commit();
            }
            return true;
        }
    }
}

我希望他打开http://example.com,但如果我转到http://example.com/page2,当我重新打开网页浏览时,他会打开http://example.com/page2 我现在已经用更多细节更新了代码。

1 个答案:

答案 0 :(得分:2)

您只需将您的网址保存到SharedPreferences,然后,如果您的SharedPreferences中存在网址,则会重新打开它。

像这样:

void someMethod() {
    WebView webView = (WebView) findViewById(R.id.webView);
    webView.setWebViewClient(new MyWebViewClient());

    String url;

    if (sPref.contains("PREFS_ID"))
        url = sPref.getString("PREFS_ID", "DEFAULT_VALUE");
    else
        url = "http://example.com";

    WebSettings webSettings = webView.getSettings();
    webSettings.setJavaScriptEnabled(true);
    webSettings.setBuiltInZoomControls(true);
    webSettings.setAllowContentAccess(true);
    webSettings.setSupportZoom(true);
    webSettings.setRenderPriority(WebSettings.RenderPriority.HIGH);

    MyWebViewClient myWebViewClient = new MyWebViewClient();
    webView.setWebViewClient(myWebViewClient);
    webView.loadUrl(url);
}

private class MyWebViewClient extends WebViewClient {
    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        if (!url.equals("YOUR_FIRSTURL")) {
            sPref.edit().putString(url, "PREFS_ID").commit();
        }
        return true;
    }
}