继续学习Android,我读了以下内容:

Question: Does the user have a choice to kill the application unless we put a menu option in to kill it? If no such option exists, how does the user terminate the application? Answer: (Romain Guy): The user doesn't, the system handles this automatically. That's what the activity lifecycle (especially onPause/onStop/onDestroy) is for. No matter what you do, do not put a "quit" or "exit" application button. It is useless with Android's application model. This is also contrary to how core applications work.

呵呵,我在Android世界里每走一步都会遇到一些问题=(

显然,你不能在Android中退出应用程序(但Android系统可以随时完全销毁你的应用程序)。这是怎么回事?我开始认为这是不可能写一个应用程序的功能作为“正常的应用程序”-用户可以退出应用程序时,他/她决定这么做。这不应该依靠操作系统来完成。

我正在尝试创建的应用程序不是Android市场的应用程序。它不是一个被大众“广泛使用”的应用程序,它是一个将在非常狭窄的商业领域使用的商业应用程序。

我其实很期待为Android平台开发,因为它解决了Windows Mobile和。net中存在的许多问题。然而,上周对我来说有点令人失望……我希望我不必放弃Android,但它现在看起来不太好=(

有办法让我真的退出应用程序吗?


当前回答

我只是想在这里为这篇文章的未来读者补充一个更正。这个细微的差别我已经不理解很长一段时间了,所以我想确保你们没有人会犯同样的错误:

如果栈上有多个activity, System.exit()不会杀死你的应用。实际发生的情况是进程被杀死,并立即重新启动,堆栈上少了一个活动。当你的应用程序被强制关闭对话框杀死时,甚至当你试图从DDMS中杀死进程时,也会发生这种情况。据我所知,这是一个完全没有记录的事实。

The short answer is, if you want to exit your application, you've got to keep track of all activities in your stack and finish() ALL of them when the user wants to exit (and no, there is no way to iterate through the Activity stack, so you have to manage all of this yourself). Even this does not actually kill the process or any dangling references you may have. It simply finishes the activities. Also, I'm not sure whether Process.killProcess(Process.myPid()) works any better; I haven't tested it.

另一方面,如果你可以将活动保留在堆栈中,还有另一个方法可以让事情变得超级简单:Activity.moveTaskToBack(true)将简单地将你的进程作为背景并显示主屏幕。

长的答案包括对这种行为背后的哲学的解释。这一理论是基于以下几个假设:

First of all, this only happens when your app is in the foreground. If it is in the background the process will terminate just fine. However, if it is in the foreground, the OS assumes that the user wants to keep doing whatever he/she was doing. (If you are trying to kill the process from DDMS, you should hit the home button first, and then kill it) It also assumes that each activity is independent of all the other activities. This is often true, for example in the case that your app launches the Browser Activity, which is entirely separate and was not written by you. The Browser Activity may or may not be created on the same Task, depending on its manifest attributes. It assumes that each of your activities is completely self-reliant and can be killed/restored in a moment's notice. (I rather dislike this particular assumption, since my app has many activities which rely on a large amount of cached data, too large to be efficiently serialized during onSaveInstanceState, but whaddya gonna do?) For most well-written Android apps this should be true, since you never know when your app is going to be killed off in the background. The final factor is not so much an assumption, but rather a limitation of the OS: killing the app explicitly is the same as the app crashing, and also the same as Android killing the app to reclaim memory. This culminates in our coup de grace: since Android can't tell if the app exited or crashed or was killed in the background, it assumes the user wants to return where they left off, and so the ActivityManager restarts the process.

仔细想想,这是适合这个平台的。首先,这正是当进程在后台被杀死,用户返回到它时所发生的情况,因此它需要在它停止的地方重新启动。其次,这是当应用程序崩溃并呈现可怕的强制关闭对话框时所发生的情况。

Say I want my users to be able to take a picture and upload it. I launch the Camera Activity from my activity, and ask it to return an image. The Camera is pushed onto the top of my current Task (rather than being created in its own Task). If the Camera has an error and it crashes, should that result in the whole app crashing? From the standpoint of the user, only the Camera failed, and they should be returned to their previous activity. So it just restarts the process with all the same Activities in the stack, minus the Camera. Since your Activities should be designed so that they can be killed and restored at the drop of a hat, this shouldn't be a problem. Unfortunately, not all apps can be designed that way, so it is a problem for many of us, no matter what Romain Guy or anyone else tells you. So, we need to use workarounds.

所以,我最后的建议是:

Don't try to kill the process. Either call finish() on all activities or call moveTaskToBack(true). If your process crashes or gets killed, and if, like me, you need the data that was in memory which is now lost, you'll need to return to the root activity. To do this, you should call startActivity() with an Intent that contains the Intent.FLAG_ACTIVITY_CLEAR_TOP flag. If you want to kill your app from the Eclipse DDMS perspective, it had better not be in the foreground, or it will restart itself. You should press the Home button first, and then kill the process.

其他回答

All of my applications have quit buttons... and I quite frequently get positive comments from users because of it. I don't care if the platform was designed in a fashion that applications shouldn't need them. Saying "don't put them there" is kind of ridiculous. If the user wants to quit... I provide them the access to do exactly that. I don't think it reduces how Android operates at all and seems like a good practice. I understand the life cycle... and my observation has been that Android doesn't do a good job at handling it.... and that is a basic fact.

在任何情况下,如果你想终止你的应用程序,你可以调用System.exit(0);。

有一个(相对)简单的设计可以让你绕过“退出”难题。让你的应用程序有一个“基本”状态(活动),这只是一个空白的屏幕。在活动的第一个onCreate,你可以启动另一个活动,你的应用程序的主要功能在其中。“退出”可以通过finish()完成第二个活动并返回到空白屏幕的底部来完成。操作系统可以在内存中保留这个空白屏幕,只要它想要…

本质上,因为你无法退出到操作系统,你只是转化成一个自我创造的虚无。

如果你有10个,20个…有多个活动正在运行,你想要完成所有活动并退出系统。

在应用程序类或常量类中创建静态数组。

常量

public class Constants {

public static ArrayList<Activity> activities = new ArrayList<Activity>();

}

在此数组中添加当前活动引用

activity = MainActivity.this; Constants.activities.add(活动);

public class MainActivity extends Activity {

    private ImageView imageButton;
    private Activity activity;


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

        activity = MainActivity.this;
        Constants.activities.add(activity);

        imageButton = (ImageView) findViewById(R.id.camera);
        imageButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                // existing app.
                if (Constants.activities != null) {
                    for (int i = 0; i < Constants.activities.size(); i++) {
                        Activity s = Constants.activities.get(i);
                        s.finish();
                    }
                }
                //super.finish();
                finish();
                android.os.Process.killProcess(android.os.Process.myPid());
                System.exit(1);
            }
        });
    }
}

不要把您的应用程序看作一个整体应用程序。它是一组UI屏幕,用户可以通过Android服务与你的“应用程序”和“功能”进行交互。

不知道你的神秘应用程序“做什么”并不重要。让我们假设它通过隧道进入某个超级安全的企业内部网,执行一些监控或交互,并保持登录状态,直到用户“退出应用程序”。因为您的IT部门命令它,所以用户必须非常清楚他们何时进入或退出内部网。因此你认为用户“退出”很重要。

这很简单。创建一个服务,在通知栏中放置一个持续通知,说“我在内部网中,或者我正在运行”。让该服务执行应用程序所需的所有功能。拥有绑定到该服务的活动,以允许用户访问与“应用程序”交互所需的UI部分。并有一个Android菜单->退出(或登出,或其他)按钮,告诉服务退出,然后关闭活动本身。

This is, for all intents and purposes exactly what you say you want. Done the Android way. Look at Google Talk or Google Maps Navigation for examples of this "exit" is possible mentality. The only difference is that pressing back button out of your activity might leave your UNIX process lying in wait just in case the user wants to revive your application. This is really no different than a modern operating system that caches recently accessed files in memory. After you quit your windows program, most likely resources that it needed are still in memory, waiting to be replaced by other resources as they are loaded now that they are no longer needed. Android is the same thing.

我真不明白你有什么问题。