首先,问题是如何出现的?
晚上复查代码,发现一个activity没有调用自己的ondestroy方法
我表示非常的费解,于是我检查了下代码。
发现再finish代码之后接了如下代码
finish();
System.exit(0);//这就是罪魁祸首
为什么这样写会出现问题
System.exit(0);//
//看一下函数的原型
public static void exit (int code)
//
Added in API level 1
//大意可以解释为,调用此方法,将会停止javaVM的执行,相当于杀死了程序
Causes the VM to stop running and the program to exit with the given exit status. If runFinalizersOnExit(boolean) has been previously invoked with a true argument, then all objects will be properly garbage-collected and finalized first.
既然我们理解了,调用exit之后,程序会被杀死,整个程序都被意外(人为)的杀死了,这是非正常情况,故,Activiy的生命周期也不会继续执行了。很好的解释了为什么ondestroy不会执行的疑问。
那么,问题是如何解决的?
将
system.exit(0);
这段代码从finish()之后移除,结果程序生命周期,执行正常。问题得到解决。
附注:我觉得这句话并不是必须写的,作为安卓开发者,应当使用finish来合理的控制app的界面,而生命周期交给系统去处理,这样才能编写出健壮的程序代码。
原文:http://www.cnblogs.com/louzhuhaha/p/4216712.html