Webview is not restoring the state after it was killed by the user

后端 未结 1 546
轻奢々
轻奢々 2020-12-19 13:28

i\'ve been in a trouble for some days to understand this issue. Basically i have a Webview which loads a website, with the first page being the login and the co

相关标签:
1条回答
  • 2020-12-19 14:03

    As you yourself pointed out since the saved state is null, you cannot possibly expect onCreate to take your webview back to the last page that was open. There are two things that you need to do:

    Make sure that your login page, which is your first page redirects to a relevent content page when it detects that the user has already logged in. Since you are already using cookies this is trivial.

    Then over ride the onPause method to save the current url of the webView.

    @Override
    protected void onPause() {
        super.onPause();
        SharedPreferences prefs = context.getApplicationContext().
                getSharedPreferences(context.getPackageName(), Activity.MODE_PRIVATE);
        Editor edit = prefs.edit();
        edit.put("lastUrl",webView.getUrl());
        edit.commit();   // can use edit.apply() but in this case commit is better
    }
    

    Then you can read this property on the onCreate method and load the url as needed. If the preference is defined load it, if not load the login page (which should redirect to first content page if already logged in)

    UPDATE here's what your onResume might look like. Also added one line to the above onPause() method.

    @Override
    protected void onResume() {
        super.onResume();
        if(webView != null) {
            SharedPreferences prefs = context.getApplicationContext().
                getSharedPreferences(context.getPackageName(), Activity.MODE_PRIVATE);
            String s = prefs.getString("lastUrl","");
            if(!s.equals("")) {
                 webView.loadUrl(s);
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题