I have an app in which I have a WebView where I display some websites. It works, clicking a link in the webpage goes to the next page in the website inside my app. But when I click the phone's back button, it takes me straight into my app. I want to go back to the previous page in the website instead. How can I do this?

Nice. I use a variation of this answer, but without the "else" block. Otherwise when the user presses back too many times they end up at a blank app "start" screen, with no option for the user to move forward.
– George ArmholdNov 12 '12 at 16:49

1

This looks like the most appropriate answer. @CaffeineComa, you could probably just code your app start screen to not show in the app "activity" history. Just add android:noHistory="true" attribute in the <activity> you want, in the AndroidManifest.xml
– LocalPCGuySep 27 '13 at 21:48

this my opinion, this should be the proper answer.
– ArvinJul 16 '13 at 2:23

2

Why this answer should be the proper answer? Any issue with the top two answers?
– ca9163d9Jan 9 '15 at 4:12

11

@dc7a9163d9 an activity might want to have several views or objects that depend on keyDown. this answer abstracts out the need for the activity to keydown dependency via webview (which is better design). also, newer apps almost exclusively use fragments as opposed to activities, and this answer supports that use case as opposed to the others
– David T.Jul 21 '15 at 4:02

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

You should the following libraries on your class handle the onBackKeyPressed.
canGoBack() checks whether the webview can reference to the previous page. If it is possible then use the goBack() function to reference the previous page (go back).

The first answer by FoamyGuy is correct but I have some additions; low reputations cannot allow me to do comments. If for some reasons your page fails to load, ensure that you set a flag to take note of the failure and then check it on the onBackPressed override. Otherwise your canGoBack()will be forever executed without heading to the actual back activity if it was there:

Thank you for your interest in this question.
Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).