Android WebView Back Button override is essential when your app is loading a webpage or inner website. You may be traveling down the website navigation tree but as soon as you hit the Android back button it closes your app. Well here is a fix for that.
The following code will check if you have traveled at least one level down the locally stored website. If yes it will throw you back on it’s home page, else the back button will function as normal.
public class MainActivity extends AppCompatActivity {
WebView myWebview;
boolean isHomePage = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getSupportActionBar().hide();
myWebview = (WebView)findViewById(R.id.myWebview);
myWebview.getSettings().setJavaScriptEnabled(true);
myWebview.getSettings().setAppCacheEnabled(true);
myWebview.getSettings().setDomStorageEnabled(true);
myWebview.setWebChromeClient(new WebChromeClient());
myWebview.setWebViewClient(new WebViewClient() {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (url.contains("android_asset")) {
isHomePage = false;
return false;
}
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
startActivity(intent);
return true;
}
});
myWebview.loadUrl("file:///android_asset/yourlocalsite/index.html");
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (Integer.parseInt(android.os.Build.VERSION.SDK) > 5
&& keyCode == KeyEvent.KEYCODE_BACK
&& event.getRepeatCount() == 0) {
Log.d("CDA", "onKeyDown Called");
onBackPressed();
return true;
}
return super.onKeyDown(keyCode, event);
}
@Override
public void onBackPressed() {
// if not home page go to home page.
if(isHomePage == false){
myWebview.loadUrl("file:///android_asset/yourlocalsite/index.html");
isHomePage = true;
// if home page exit app.
}else {
Log.d("CDA", "onBackPressed Called");
Intent setIntent = new Intent(Intent.ACTION_MAIN);
setIntent.addCategory(Intent.CATEGORY_HOME);
setIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(setIntent);
}
}
}
You can extend upon this if you like, you could technically build a stack to trace where you went and build your logic that way if you would like to do various things based on where you are.
I hopes this helps, Cheers!