How to close my application programmatically in android?

11,932

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

Share:
11,932
Anish Kumar
Author by

Anish Kumar

Updated on August 23, 2022

Comments

  • Anish Kumar
    Anish Kumar almost 2 years

    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();
    }