How to quit android application programmatically

前端 未结 30 1949
迷失自我
迷失自我 2020-11-22 03:06

I Found some codes for quit an Android application programatically. By calling any one of the following code in onDestroy() will it quit application entirely?

相关标签:
30条回答
  • 2020-11-22 03:33

    It's not a good decision, cause it's against the Android's application processing principles. Android doesn't kill any process unless it's absolutely inevitable. This helps apps start faster, cause they're always kept in memory. So you need a very special reason to kill your application's process.

    0 讨论(0)
  • 2020-11-22 03:34

    First of all, this approach requires min Api 16.

    I will divide this solution to 3 parts to solve this problem more widely.

    1. If you want to quit application in an Activity use this code snippet:

    if(Build.VERSION.SDK_INT>=16 && Build.VERSION.SDK_INT<21){
        finishAffinity();
    } else if(Build.VERSION.SDK_INT>=21){
        finishAndRemoveTask();
    }
    

    2. If you want to quit the application in a non Activity class which has access to Activity then use this code snippet:

    if(Build.VERSION.SDK_INT>=16 && Build.VERSION.SDK_INT<21){
        getActivity().finishAffinity();
    } else if(Build.VERSION.SDK_INT>=21){
        getActivity().finishAndRemoveTask();
    }
    

    3. If you want to quit the application in a non Activity class and cannot access to Activity such as Service I recommend you to use BroadcastReceiver. You can add this approach to all of your Activities in your project.

    Create LocalBroadcastManager and BroadcastReceiver instance variables. You can replace getPackageName()+".closeapp" if you want to.

    LocalBroadcastManager mLocalBroadcastManager;
    BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if(intent.getAction().equals(getPackageName()+".closeapp")){
                if(Build.VERSION.SDK_INT>=16 && Build.VERSION.SDK_INT<21){
                    finishAffinity();
                } else if(Build.VERSION.SDK_INT>=21){
                    finishAndRemoveTask();
                }
            }
        }
    };
    

    Add these to onCreate() method of Activity.

    mLocalBroadcastManager = LocalBroadcastManager.getInstance(this);
    IntentFilter mIntentFilter = new IntentFilter();
    mIntentFilter.addAction(getPackageName()+".closeapp");
    mLocalBroadcastManager.registerReceiver(mBroadcastReceiver, mIntentFilter);
    

    Also, don't forget to call unregister receiver at onDestroy() method of Activity

    mLocalBroadcastManager.unregisterReceiver(mBroadcastReceiver);
    

    For quit application, you must send broadcast using LocalBroadcastManager which I use in my PlayService class which extends Service.

    LocalBroadcastManager localBroadcastManager = LocalBroadcastManager.getInstance(PlayService.this);
    localBroadcastManager.sendBroadcast(new Intent(getPackageName() + ".closeapp"));
    
    0 讨论(0)
  • 2020-11-22 03:34

    I think what you are looking for is this

    activity.moveTaskToBack(Boolean nonRoot);
    
    0 讨论(0)
  • 2020-11-22 03:35

    Please think really hard about if you do need to kill the application: why not let the OS figure out where and when to free the resources?

    Otherwise, if you're absolutely really sure, use

    finish();
    

    As a reaction to @dave appleton's comment: First thing read the big question/answer combo @gabriel posted: Is quitting an application frowned upon?

    Now assuming we have that, the question here still has an answer, being that the code you need if you are doing anything with quitting is finish(). Obviously you can have more than one activity etc etc, but that's not the point. Lets run by some of the use-cases

    1. You want to let the user quit everything because of memory usage and "not running in the background? Doubtfull. Let the user stop certain activities in the background, but let the OS kill any unneeded recourses.
    2. You want a user to not go to the previous activity of your app? Well, either configure it so it doesn't, or you need an extra option. If most of the time the back=previous-activity works, wouldn't the user just press home if he/she wants to do something else?
    3. If you need some sort of reset, you can find out if/how/etc your application was quit, and if your activity gets focus again you can take action on that, showing a fresh screen instead of restarting where you were.

    So in the end, ofcourse, finish() doesn't kill everthing, but it is still the tool you need I think. If there is a usecase for "kill all activities", I haven't found it yet.

    0 讨论(0)
  • 2020-11-22 03:35

    Easy and simple way to quit from the application

    Intent homeIntent = new Intent(Intent.ACTION_MAIN);
    homeIntent.addCategory(Intent.CATEGORY_HOME);
    homeIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    startActivity(homeIntent);
    
    0 讨论(0)
  • 2020-11-22 03:36

    finishAffinity();

    System.exit(0);

    If you will use only finishAffinity(); without System.exit(0); your application will quit but the allocated memory will still be in use by your phone, so... if you want a clean and really quit of an app, use both of them.

    This is the simplest method and works anywhere, quit the app for real, you can have a lot of activity opened will still quitting all with no problem.

    example on a button click

    public void exitAppCLICK (View view) {
    
        finishAffinity();
        System.exit(0);
    
    }
    

    or if you want something nice, example with an alert dialog with 3 buttons YES NO and CANCEL

    // alertdialog for exit the app
    AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
    
    // set the title of the Alert Dialog
    alertDialogBuilder.setTitle("your title");
    
    // set dialog message
    alertDialogBuilder
            .setMessage("your message")
            .setCancelable(false)
            .setPositiveButton("YES"),
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog,
                                            int id) {
                            // what to do if YES is tapped
                            finishAffinity();
                            System.exit(0);
                        }
                    })
    
            .setNeutralButton("CANCEL"),
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog,
                                            int id) {
                            // code to do on CANCEL tapped
                            dialog.cancel();
                        }
                    })
    
            .setNegativeButton("NO"),
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog,
                                            int id) {
                            // code to do on NO tapped
                            dialog.cancel();
                        }
                    });
    
    AlertDialog alertDialog = alertDialogBuilder.create();
    
    alertDialog.show();
    
    0 讨论(0)
提交回复
热议问题