我找到了一些以编程方式退出Android应用程序的代码。通过在onDestroy()中使用以下任何代码,它会完全退出应用程序吗?

System.runFinalizersOnExit(真正的) (或) android.os.Process.killProcess (android.os.Process.myPid ());

我不想在点击退出按钮后在后台运行我的应用程序。 请告知我是否可以使用这些代码中的任何一个来退出我的应用程序?如果可以,我可以使用哪个代码?在Android中退出应用程序是一个好方法吗?


如果您确实需要关闭应用程序,请认真考虑一下:为什么不让操作系统自行决定何时何地释放资源呢?

否则,如果你非常确定,就用

finish();

作为对@dave appleton评论的回应:第一件事是阅读大问题/答案组合@gabriel的帖子:退出应用程序是不受欢迎的吗?

现在假设我们有了这个,这里的问题仍然有一个答案,如果你要做任何关于退出的事情,你需要的代码是finish()。显然你可以有不止一项活动等等,但这不是重点。让我们看一些用例

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. 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? 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.

所以最后,当然,finish()不会杀死所有东西,但我认为它仍然是你需要的工具。如果有“杀死所有活动”的用例,我还没有找到。


这不是一个好的决定,因为它违背了Android的应用程序处理原则。Android不会终止任何进程,除非绝对不可避免。这有助于应用程序启动得更快,因为它们总是保存在内存中。因此,您需要一个非常特殊的理由来终止应用程序的进程。


我认为应用程序在某些情况下应该被杀死。例如,有一个应用程序需要登录后才能使用。登录活动有两个按钮,“登录”和“取消”。当你点击“取消”按钮时,它肯定意味着“终止应用程序”。没有人希望应用程序在后台运行。所以我同意在某些情况下需要关闭应用程序。


android中没有退出应用程序, SampleActivity.this.finish ();将完成当前活动。

当你从一个活动切换到另一个活动时,要坚持完成前一个活动

Intent homeintent = new Intent(SampleActivity.this,SecondActivity.class);
startActivity(homeintent);
SampleActivity.this.finish();

放弃一份申请是不受欢迎的吗?通过这个链接。它回答了你的问题。系统负责终止应用程序的工作。

假设你有两个活动A和B,你从A导航到B,当你点击返回按钮,你的活动B从背堆栈弹出并销毁。后堆栈活动A中的前一个活动集中。

您应该让系统决定何时终止应用程序。

公共无效处理()

当您的活动完成并应该关闭时调用它。

假设你有很多活动。你可以使用动作条。点击主页图标导航到应用程序的MainActivity。在MainActivity中单击返回按钮退出应用程序。


这可能很晚了,而且根据指导方针,您不应该自己处理生命周期过程(因为操作系统为您做了)。一个建议是,你在你所有的活动中注册一个广播接收器,在他们的onReceive()中使用“finish()”&每当你希望退出时,你可以简单地传递一个意图,指示所有活动必须关闭..... 尽管要确保在onDestroy()方法中“取消注册”接收器。


我不知道这是否会引起不满,但我就是这么做的……

步骤1 -我通常有一个类,其中包含我想全局访问的方法和变量。在本例中,我将其称为“App”类。在类中为应用程序的每个活动创建一个静态Activity变量。然后创建一个名为“close”的静态方法,如果这些Activity变量不为空,它将在每个Activity变量上运行finish()方法。如果你有一个主/父活动,最后关闭它:

public class App
{
    ////////////////////////////////////////////////////////////////
    // INSTANTIATED ACTIVITY VARIABLES
    ////////////////////////////////////////////////////////////////

        public static Activity activity1;
        public static Activity activity2;
        public static Activity activity3;

    ////////////////////////////////////////////////////////////////
    // CLOSE APP METHOD
    ////////////////////////////////////////////////////////////////

        public static void close()
        {
            if (App.activity3 != null) {App.activity3.finish();}
            if (App.activity2 != null) {App.activity2.finish();}
            if (App.activity1 != null) {App.activity1.finish();}
        }
}

步骤2 -在每个活动中,重写onStart()和onDestroy()方法。在onStart()中,将App类中的静态变量设置为"this"。在onDestroy()中,将其设置为null。例如,在“Activity1”类中:

@Override
public void onStart()
{
    // RUN SUPER | REGISTER ACTIVITY AS INSTANTIATED IN APP CLASS

        super.onStart();
        App.activity1 = this;
}

@Override
public void onDestroy()
{
    // RUN SUPER | REGISTER ACTIVITY AS NULL IN APP CLASS

        super.onDestroy();
        App.activity1 = null;
}

步骤3 -当你想关闭你的应用程序时,只需从任何地方调用app .close()。所有实例化的活动将关闭!因为你只是关闭活动,而不是杀死应用程序本身(如你的例子),Android可以自由地从那里接管,并做任何必要的清理。

再说一次,我不知道这是否会因为任何原因而引起不满。如果是这样的话,我很乐意阅读关于为什么会这样以及如何改进的评论!


我觉得你要找的是这个

activity.moveTaskToBack(Boolean nonRoot);

getActivity().finish();
System.exit(0);

这是退出应用程序的最佳方式!!

对我来说最好的解决方案。


从API 16开始,你可以使用finishAffinity方法,它似乎非常接近于通过它的名称和Javadoc描述关闭所有相关的活动:

this.finishAffinity();

Finish this activity as well as all activities immediately below it in the current task that have the same affinity. This is typically used when an application can be launched on to another task (such as from an ACTION_VIEW of a content type it understands) and the user has used the up navigation to switch out of the current task and into its own task. In this case, if the user has navigated down into any other activities of the second application, all of those should be removed from the original task as part of the task switch. Note that this finish does not allow you to deliver results to the previous activity, and an exception will be thrown if you are trying to do so.


从API 21开始,您可以使用非常类似的命令

finishAndRemoveTask();

完成此任务中的所有活动,并将其从最近任务列表中移除。


public void quit() {
        int pid = android.os.Process.myPid();
        android.os.Process.killProcess(pid);
        System.exit(0);
    }

这将杀死任何东西;)

int p = android.os.Process.myPid();
android.os.Process.killProcess(p);

正确和准确的解决方案退出应用程序的按钮点击是使用下面的代码:

//On Button Back按下事件

public void onBackPressed()
{ 
   moveTaskToBack(true);
   finish();
}

只需要使用finish()返回键按onKeypressed()


你可以使用API 21中的finishAndRemoveTask ()

finishAndRemoveTask () 完成此任务中的所有活动,并将其从最近任务列表中移除。


在on backpressed override方法中编写这段代码

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

这取决于你想多快关闭你的应用程序。

关闭应用程序的安全方法是finishAffinity();

它关闭你的应用程序后,所有进程完成处理。 这可能需要一些时间。 如果你以这种方式关闭你的应用程序,并在短时间后重新启动它,你的新应用程序可能运行在同一个进程中。旧应用程序的所有未完成的进程和单例对象。

如果你想确保你的应用程序已经完全关闭,请使用System.exit(0);

这将立即关闭你的应用程序。 但这是有可能的,你破坏了你的应用程序已经打开的文件或共享首选项的编辑没有完成。所以要小心使用。

如果您将看门狗与长时间运行的任务结合使用,您可以看到不同方法的影响。

new ANRWatchDog(2000).setANRListener(new ANRWatchDog.ANRListener() {
    public void onAppNotResponding(ANRError error) {
        MainActivity.this.finishAffinity();
        System.exit(0);
    }
}).start();
for(int i = 0; i < 10; ++i){
    --i;
}

这会在2秒后杀死你的应用,而不显示ANR对话框或类似的东西。如果你删除System.exit(0),运行这段代码并在应用程序关闭后重新启动应用程序,你会遇到一些奇怪的行为,因为无休止的循环仍在运行。


如果你在Activity中,最好使用finish(),如果你在Fragment中,最好使用getActivity().finish()。

如果你想完全退出应用程序,那么使用:

getActivity().finish();
System.exit(0);

finishAffinity ();

System.exit(0);

如果你只使用finishAffinity();没有system . exit (0);你的应用程序将退出,但分配的内存仍然会被你的手机使用,所以…如果你想要一个干净的,真正退出的应用程序,使用他们两个。

这是最简单的方法,在任何地方都适用,退出应用程序,你可以有很多活动打开仍然会退出所有没有问题。

示例对一个按钮进行单击

public void exitAppCLICK (View view) {

    finishAffinity();
    System.exit(0);

}

或者如果你想要一些漂亮的东西,例如一个警报对话框,有3个按钮是,否和取消

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

试试这个

int pid = android.os.Process.myPid();
android.os.Process.killProcess(pid);

我发现从一个活动中退出应用程序的最简单的方法是,不破坏Android的逻辑,也不需要在现有的活动中添加更多的代码和传递额外的东西:

public static void quitApplication (Activity currentActivity) {
    Intent intent = new Intent (currentActivity, QuitApplicationActivity.class);
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);

    currentActivity.startActivity (intent);
    currentActivity.finish ();
}

QuitApplicationActivity是:

public class QuitApplicationActivity extends AppCompatActivity {

    @Override
    protected void onCreate (Bundle savedInstanceState) {
        super.onCreate (savedInstanceState);

        finish ();
    }
}

简单和简单的方法退出应用程序

Intent homeIntent = new Intent(Intent.ACTION_MAIN);
homeIntent.addCategory(Intent.CATEGORY_HOME);
homeIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(homeIntent);

创建一个ExitActivity并在manifest中声明它。并调用exitactivity。exit(context)来退出应用程序。

public class ExitActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        finish();
    }

    public static void exit(Context context) {
        Intent intent = new Intent(context, ExitActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
        context.startActivity(intent);
    }

}

首先,这种方法要求最小Api 16。

为了更广泛地解决这个问题,我将把这个解决方案分为3个部分。

1. 如果你想在Activity中退出应用程序,请使用以下代码片段:

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

2. 如果你想退出一个非Activity类的应用程序,可以访问Activity,那么使用下面的代码片段:

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

3.如果你想在非Activity类中退出应用程序,并且不能访问Activity(如Service),我建议你使用BroadcastReceiver。您可以将此方法添加到项目中的所有活动中。

创建LocalBroadcastManager和BroadcastReceiver实例变量。您可以替换getPackageName()+"。Closeapp”如果你想的话。

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

将这些添加到Activity的onCreate()方法。

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

另外,不要忘记在Activity的onDestroy()方法调用unregister receiver

mLocalBroadcastManager.unregisterReceiver(mBroadcastReceiver);

对于退出应用程序,你必须使用LocalBroadcastManager发送广播,我在我的PlayService类中使用,它扩展了服务。

LocalBroadcastManager localBroadcastManager = LocalBroadcastManager.getInstance(PlayService.this);
localBroadcastManager.sendBroadcast(new Intent(getPackageName() + ".closeapp"));

要退出应用程序,您可以使用以下命令:

getActivity().finish();
Process.killProcess(Process.myPid());
System.exit(1);

也可以调用下面的方法来停止服务:

private void stopServices() {        
    final ActivityManager activityManager = SystemServices.getActivityManager(context);
    final List<ActivityManager.RunningServiceInfo> runningServices = activityManager.getRunningServices(Integer.MAX_VALUE);
    final int pid = Process.myPid();
    for (ActivityManager.RunningServiceInfo serviceInfo : runningServices) {
        if (serviceInfo.pid == pid && !SenderService.class.getName().equals(serviceInfo.service.getClassName())) {
            try {
                final Intent intent = new Intent();
                intent.setComponent(serviceInfo.service);
                context.stopService(intent);
            } catch (SecurityException e) { 
                 // handle exception
            }
        }
    }
}

只是在终止应用程序的残酷方法列表中添加一个:

Process.sendSignal (Process.myPid (), Process.SIGNAL_KILL);


我们希望代码健壮而简单。 该解决方案适用于旧设备和新设备。

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
        getActivity().finishAffinity();
    } else{
        getActivity().finish();
        System.exit( 0 );
    }

@Sivi的回答关闭了应用程序。但返回时,如果你有一些子活动,另一个未完成的活动可能会打开。我添加了noHistory:true到我的活动,所以应用程序在返回时从MainActivity开始。

<activity 
      android:name=".MainActivity"
      android:noHistory="true">
</activity>

如果你正在使用Kotlin,退出应用程序的正确方法和System.exit()的替代方法是一个内置方法

exitProcess(0)

请参见文档。

数字0作为参数表示打算退出,并且没有发生错误。


类似于@MobileMateo,但是用的是Kotlin

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
    this.finishAffinity()
} else{
    this.finish()
    System.exit(0)
}

朋友只需添加此函数以编程方式退出应用程序 # java

public void onBackPressed() 
{

    finishAffinity();
    System.exit(0);
}

如果你想关闭你的应用:

对于API >= 21,使用:

finishAndRemoveTask();

API < 21使用:

finishAffinity();