0

I'm writing a simple app with 4 activities. I'll describe it quickly so you understand what I'm trying to achieve.

First activity - MainActivity has some TextEdit fields that collect 2 input parameters - number of reps and length of pause in seconds. A button takes me to the second activity: WorkActivity - all this does is it starts counting until I press 'done' then it either calls PauseActivity, or if it has been the last rep, calls OverviewActivity. PauseActivity counts down the seconds until next rep, then beeps at me to let me know it's time, and shows WorkActivity again. OverviewActivity shows total workout time and times for each rep.

It also features a button that should just end the app. I know exiting your apps is not really in line with the Android application life cycle philosophy, but I need it (or something like it to happen). I have a singleton controller class that keeps track of the reps and logs the time. I can kill this instance (or fake its death, so a new one will be created), but when I "close" the app and then click it again, I get the OverviewActivity instead of the expected MainActivity.

I expected that calling System.exit(0) would take care of things, simply shut down the application, so it will have to initialize anew when run again. Instead the whole thing started acting really derpy. When I click the button that calls System.exit(0), instead of vanishing my app sort of restarts. It shows the WorkActivity, and starts counting. When I click the done button (which should take me to PauseActivity) I get an exception. The application crashes - and then restarts again. This will repeat until I hit the homescreen button, and the app remains in this useless state until I kill it in application manager.

Also, I'm not exactly sure, but I think the System.exit(0) call (or the subsequent crash) disconnects the debugger, cause I've been unable to get Eclipse to hit any breakpoints afterwards. This means I can't really see the actual exception that occurs.

Can someone shed some light on this? Is there a way to use System.exit(0) correctly?

In the absence of this option, what would be the correct way of handling this? I need the app to: - when I click the final 'Done' button the Home button or the Back button, dispose of the Controller, (and everything else if possible), stop counting (if any timer is running) and essentially shut itself down) - when I click the app's icon again, to show me a new instance (or one that appears new) with the MainActivity to greet me and all other activities in their default state.

4

1 回答 1

5

使用 System.exit(0) 是一种不好的做法。

在这种情况下调用 exit() 将终止进程,杀死您的其他组件并可能破坏您的数据。当然,操作系统可能不太关心,但您的用户可能不喜欢它。

如果其他应用程序已经用尽了内部 Dalvik 堆限制,那么自愿终止您的进程将无济于事。无论设备有多少物理内存,操作系统都会限制 Dalvik 在任何进程中用于堆分配的内存量。因此,系统可能有一半的内存可用,并且特定应用程序仍然会遇到 OOM。

不要使用 System.exit(0);相反,您可以只使用finish()。

Intent intent = new Intent(this, Activity2.class);
startActivity(intent);
finish();
于 2013-07-27T16:09:00.563 回答