-6

I need functionality to exit from the complete application while pressing back button. currently i have a script that ask to press twice to exit application,

in that it finish the current activity but does not exits from application old visited activities are remain same. here is my code that i am using.

int i = 1;
@Override
public void onBackPressed() {       
    if (i == 1) {
        Toast.makeText(getApplicationContext(), "Press back once more to exit.", Toast.LENGTH_SHORT).show();
    } else if(i>1) {
        finish();
    }
    i++;
}
Ravi
  • 34,851
  • 21
  • 122
  • 183
Deepak
  • 523
  • 4
  • 24

3 Answers3

0

please try below code.

step 1: Create on Constant class

public class Constant
{
    public static int ACT_COUNT=0;
}

step 2:Create BaseActivity class

public class BaseActivity extends Activity
{
private static long back_pressed;
    @Override
    protected void onCreate(Bundle arg0)
    {
    super.onCreate(arg0);
    Constant.ACT_COUNT++;
    }


   @Override
   public void onBackPressed()
   {
    /** If you want to take confirmation then display Alert here...**/
        if(Constant.ACT_COUNT<=1)
        {
            if (back_pressed + 2000 > System.currentTimeMillis()) 
               finish(); /** otherwise directly exit from here...**/
            else 
               Toast.makeText(getBaseContext(), "Press once again to exit!", Toast.LENGTH_SHORT).show();

            back_pressed = System.currentTimeMillis();
        }
        else
            super.onBackPressed();
    }

    @Override
    protected void onDestroy()
    {
        super.onDestroy();
        Constant.ACT_COUNT--;
    }

}

NOTE: You have to use BaseActivity instead of Activity in your application except login activity and registration activity if it is in your application.

Bhavesh Jethani
  • 3,891
  • 4
  • 24
  • 42
0

finish(); doesn't close the application, just finishes the current activity and takes you back to the previous activity running. Instead use System.exit(1);

James Ele
  • 111
  • 3
  • 13
-2

Get back press work only at second press and notify user to press again to exit.

private static long back_pressed;

@Override
public void onBackPressed()
{
        /** If you want to take confirmation then display Alert here...**/
        if (back_pressed + 2000 > System.currentTimeMillis()) 
           finish(); /** otherwise directly exit from here...**/
        else 
           Toast.makeText(getBaseContext(), "Press once again to exit!", Toast.LENGTH_SHORT).show();

        back_pressed = System.currentTimeMillis();
}

Ref. Android Snippet

Pratik Butani
  • 60,504
  • 58
  • 273
  • 437