访问上次加载 URL

Visit Last Loaded URL

我正在 Xamarin android 中制作一个用户导航的应用程序。该应用程序包含网络视图。当用户打开 webview 时,url 被加载并且可以完成浏览。当他结束应用程序并再次打开时,会再次加载 URL 而不是查看上次访问的 URL.

我不知道我做错了什么。

    protected override void OnCreate(Bundle savedInstanceState)
    {
        base.OnCreate(savedInstanceState);

        // Set our view from the "main" layout resource
        SetContentView(Resource.Layout.Main);
        webView = FindViewById<WebView>(Resource.Id.webView1);
        webView.SetWebViewClient(new MyWebClient());
        CookieManager.Instance.SetAcceptCookie(true);
        webView.Settings.JavaScriptEnabled = true;
        webView.Settings.SetAppCacheEnabled(true);
        webView.LoadUrl(getUrl());
        webView.SetPadding(0, 0, 0, 0);


        webView.Settings.SetSupportZoom(true);

    }
    public void saveUrl(String url)
    {
        ISharedPreferences sp = GetSharedPreferences("SP_WEBVIEW_PREFS", FileCreationMode.Private);
        ISharedPreferencesEditor editor = sp.Edit();
        editor.PutString("SAVED_URL", url);
        editor.Commit();
    }
    public String getUrl()
    {

        ISharedPreferences sp = GetSharedPreferences("SP_WEBVIEW_PREFS", FileCreationMode.Private);
        //If you haven't saved the url before, the default value will be google's page
        return sp.GetString("SAVED_URL", "http://google.com");

    }
    public void onPageFinished(WebView view, String url)
    {
        this.onPageFinished(view, url);
        saveUrl(url);

    }
}

internal class MyWebClient : WebViewClient
{
    public override bool ShouldOverrideUrlLoading(WebView view, string url)
    {
        view.LoadUrl(url);
        return false;
    }
}

您已将 onPageFinished 方法放入 Activity 中。它应该在 MyWebClient class 中被覆盖,如下所示:

internal class MyWebClient : WebViewClient 
{ 
     public override bool ShouldOverrideUrlLoading(WebView view, string url) 
     { 
           view.LoadUrl(url); 
           return false; 
     } 


     public override void OnPageFinished(WebView view, String url) 
     { 
           base.OnPageFinished(view, url); 

           //Save the url here. 
           //This method itself gives you the last url loaded as it's url Parameter.
           ISharedPreferences sp = Application.Context.GetSharedPreferences("SP_WEBVIEW_PREFS", FileCreationMode.Private);
           ISharedPreferencesEditor editor = sp.Edit();
           editor.PutString("SAVED_URL", url);
           editor.Commit().
     }
}

这个方法会在URL加载完成后自动调用,然后你将加载的URL存储在这个方法中。