getOnBackPressedDispatcher ejemplo
OnBackPressedCallback onBackPressedCallback = new OnBackPressedCallback( true ) {
boolean doubleBackToExitPressedOnce=false;
@Override
public void handleOnBackPressed() {
if (doubleBackToExitPressedOnce) {
ActivityCompat.finishAffinity( FirstActivity.this );
Log.e( "Click", "double back" );
return;
}
this.doubleBackToExitPressedOnce = true;
Toast.makeText(FirstActivity.this,getStrin(R.string.exitapp),Toast.LENGTH_SHORT).show();
new Handler().postDelayed( new Runnable() {
@Override
public void run() {
doubleBackToExitPressedOnce=false;
}
}, 2000);
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate( savedInstanceState );
setContentView( R.layout.activity_first );
//getting bottom navigation view and attaching the listener
getOnBackPressedDispatcher().addCallback( this, onBackPressedCallback );
}