4

I need to quit my application, I have referred all the links in Stack Overflow and also on other sites, I have used finishAffinity() , finish(), System.exit(0) still I am not able to achieve it. I am overriding onBackPressed method in Main Activity and terminating the application.

Actually it works fine when I press back button after launching the application. But when I move on to other activities and come back to MainActivity, it is not working. If I use finishAffinity() it is opening my Camera Activity which is one of my Activity in the project. If I use finish() it is opening my second page activity.

I will post my code for reference.

MainActivity.Java

 @Override
public void onBackPressed()
{

    if (back_pressed + 2000 > System.currentTimeMillis())
    {
        Log.e("called", "back pressed");
       finish();


    }

    else {

        Toast.makeText(getBaseContext(), "Press twice to exit!", Toast.LENGTH_SHORT).show();
    }

    back_pressed = System.currentTimeMillis();
}
halfer
  • 19,824
  • 17
  • 99
  • 186
Anish Kumar
  • 478
  • 4
  • 12
  • 27
  • 1
    Possible duplicate of [How to quit android application programmatically](http://stackoverflow.com/questions/6330200/how-to-quit-android-application-programmatically) – Gavriel Jan 29 '16 at 09:38
  • What do you mean on "come back to MainActivity, it is not working"? – Gavriel Jan 29 '16 at 09:39
  • People use System.exit() but these abrupt things are like nightmares to me, [see this approach](http://stackoverflow.com/a/9735524/681929) , I guess its clean. – nobalG Jan 29 '16 at 09:42
  • EDITED: while Coming Back to MainActivity, it is not working. – Anish Kumar Jan 29 '16 at 09:47
  • @nobalG I used it. Still I am not able to close my application. – Anish Kumar Jan 29 '16 at 09:51

1 Answers1

5

Whenever you wish to exit all open activities, you should press a button which loads the first Activity that runs when your application starts then clear all the other activities, then have the last remaining activity finish. to do so apply the following code in ur project

Intent intent = new Intent(getApplicationContext(), FirstActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra("EXIT", true);
startActivity(intent);

The above code finishes all the activities except for FirstActivity. Then we need to finish the FirstActivity's Enter the below code in Firstactivity's oncreate

if (getIntent().getExtras() != null && getIntent().getExtras().getBoolean("EXIT", false)) {
    finish();
}

and you are done....

For More Detail ..exit android application programmatically

Community
  • 1
  • 1
Harshad
  • 1,344
  • 1
  • 10
  • 25