Webview does not restore state after user has been killed by user

I had problems for several days to understand this problem. Basically, I have a Webview that loads a website, with the first page being a login, and the content follows after logging in.

Each user check is performed through the site. Thus, there is nothing that could be stored in a SharedPreference . Im using only the url in this scenario.

so onCreate after killing my application, web browsing does not restore the previous state until his death.

I assume this is because savedinstancestate is null and loads the url again after the application is killed.

I have session cookies and stuff.

I was wondering if anyone has a suggestion.

ps I'm new to Android.

+5
java android android-webview
Sep 28 '15 at 22:33
source share
1 answer

As you yourself indicated, since the saved state is null, you cannot expect onCreate to return your webview to the last page opened. You need to do two things:

Make sure your login page, which is your first page, is redirected to the relevant content page when it detects that the user has already registered. Since you already use cookies, this is trivial.

Then move the onPause method to save the current web browser URL.

 @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 } 

You can then read this property in the onCreate method and load the URL as needed. If preference is defined, download it if you don’t download the login page (which should be redirected to the first page of content if it is already logged in)

UPDATE is 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); } } } 
+5
Sep 29 '15 at 3:11
source share
β€” -



All Articles