How to close the android app on back press

In this article, we are going to learn how to exit the application when clicking on the back press. If you didn’t write this code for back press it will go to previous activity.

The App looks Like

Github: https://github.com/rincemathew/HowtoCloseApponBackPress

MainActivity.java

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


    }

    @Override
    public void onBackPressed() {
        Intent close = new Intent(Intent.ACTION_MAIN);
        close.addCategory(Intent.CATEGORY_HOME);
        close.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(close);
    }
}

Keep exploring more tutorial from this site. In case of any queries make a comment. Happy coding!!!!

Add a Comment

Your email address will not be published. Required fields are marked *