Search code examples
androidandroid-intentonbackpressedandroid-snackbar

How to exit on double back press with showing the snackbar dialogue of exit?


I wanted to make a snackbar dialog on double press to exit...(java)

Requested with these

  1. On 1st time back pressed show dialogue " press back again to exit " for 2 seconds

  2. On pressing back again show "do you want to exit ? " with the confirmation button for 2 seconds

As like below -

enter image description here


Solution

  • Create id for your layout in activity_main

    CoordinatorLayout coordinatorLayout;
    
    @Override
    public void onBackPressed() {     
        coordinatorLayout= (CoordinatorLayout) findViewById(R.id.coordinatorLayout);
    if (!doubleBackToExitPressedOnce) {
                this.doubleBackToExitPressedOnce = true;
                Snackbar.make(coordinatorLayout, "Do you really want to exit?", Snackbar.LENGTH_LONG)
                    .setAction("YES", new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        //button action here
                        System.exit(0);
                    }
                }).setActionTextColor(Color.YELLOW)
                  .show();
                new Handler().postDelayed(new Runnable() {
    
                    @Override
                    public void run() {
                        doubleBackToExitPressedOnce = false;
                    }
                }, 2000);
            } 
    

    Hope this helps