How to close Android application?

后端 未结 22 1195
小蘑菇
小蘑菇 2020-11-22 07:17

I want to close my application, so that it no longer runs in the background.

How to do that? Is this good practice on Android platform?

If I rely on the \"ba

22条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-22 08:16

    Simply write the following code in onBackPressed:

    @Override
    public void onBackPressed() {
        // super.onBackPressed();
    
        //Creating an alert dialog to logout
        AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
        alertDialogBuilder.setMessage("Do you want to Exit?");
        alertDialogBuilder.setPositiveButton("Yes",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface arg0, int arg1) {
                        Intent intent = new Intent(Intent.ACTION_MAIN);
                        intent.addCategory(Intent.CATEGORY_HOME);
                        startActivity(intent);
                    }
                });
    
        alertDialogBuilder.setNegativeButton("No",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface arg0, int arg1) {
    
                    }
                });
    
        //Showing the alert dialog
        AlertDialog alertDialog = alertDialogBuilder.create();
        alertDialog.show();
    }
    

提交回复
热议问题