Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Back button pressed

Tags:

android

I have multiple activities with 5 different screens.How should i handle a situation if a back key is pressed ??in First Screen and other screens ?? finish() and System.exit() is not working ..What should i do to exit my application if the Back button is pressed ?? The below coding does not work ?Please suggest me a way to exit an application having multiple screens

 public boolean onKeyDown(int keyCode, KeyEvent event) 
 {
    if (keyCode == KeyEvent.KEYCODE_BACK) 
     {
        AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
                this);

        new AlertDialog.Builder(this) .setMessage("Are you sure you want to exit?")
           .setCancelable(true)
          .setPositiveButton("Yes", new DialogInterface.OnClickListener() 
           { 
             public void onClick(DialogInterface hi, int dd) 
             {

                Intent exitIntent = new Intent(Mapper.this,SplashActivity.class);
                exitIntent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP|Intent.FLAG_ACTIVITY_CLEAR_TOP);
                SplashActivity.mHandler.sendEmptyMessage(0);                   
                startActivity(exitIntent);    


             }
           }
          )
         .setNegativeButton("Cancel", new DialogInterface.OnClickListener() 
         { 
           public void onClick(DialogInterface hi, int dd) 
           {

           }
         }
         );
        AlertDialog alertDialog = alertDialogBuilder.create();

            // show it
            alertDialog.show();
      //AlertDialog alert1 = alt_bld.create();
      //alert1.setTitle("EXIT");
      //alert1.show(); 
       return true; 
     }
     return super.onKeyDown(keyCode, event);
 }

  And in Start.Class:
  public boolean onKeyDown(int keyCode, KeyEvent event) 
{
    if (keyCode == KeyEvent.KEYCODE_BACK || keyCode == KeyEvent.KEYCODE_HOME) 
    {
        mHandler.removeCallbacksAndMessages(null);
        SplashActivity.this.finish();
    }

    return super.onKeyDown(keyCode, event); 
}
like image 501
Sindu Avatar asked Nov 14 '12 21:11

Sindu


1 Answers

Just override onBackPressed() like this...

@Override
public void onBackPressed()
{
    finish();  
}
like image 176
Artyom Kiriliyk Avatar answered Oct 28 '22 04:10

Artyom Kiriliyk