简体   繁体   中英

How to close my application programmatically in android?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM