Android编程之Activity中onDestroy()调用分析
本文分析了Android编程之Activity中onDestroy()调用方法。分享给大家供大家参考,具体如下:
刚刚一个BUG让我发现,如果activity实现了一个回调接口,然后使用this设置给需要回调接口的方法,这种应用场景比较常见,最常见的就是实现onClickListener接口,然后findViewById().setOnClickListenr(this)
如果,这个回调接口设置到了一个静态对象(单例模式),当activityfinish()的时候(按返回键,回到桌面),则activity不会被调用onDestroy(),原因可能是activity对象还在被引用!
此时你再点击图标回到应用,onCreate()再次调用!
很明显,如果你把资源释放放在了onDestroy()里面,就会导致内存泄露!
那有没有解决办法呢?有的
你可以在onPause()方法里面判断isFinishing(),正常调用finish()后activity的回调过程是onPause、onStop、onDestroy,倘若出现上面的情况,只到onPause!但是isFinishing()标志还是为true!你可以释放资源了。
我们来看下 onDestroy的官方解释:
protectedvoidonDestroy() AddedinAPIlevel1 Performanyfinalcleanupbeforeanactivityisdestroyed.Thiscanhappeneitherbecausetheactivityisfinishing(someonecalledfinish()onit,orbecausethesystemistemporarilydestroyingthisinstanceoftheactivitytosavespace.YoucandistinguishbetweenthesetwoscenarioswiththeisFinishing()method. Note:donotcountonthismethodbeingcalledasaplaceforsavingdata!Forexample,ifanactivityiseditingdatainacontentprovider,thoseeditsshouldbecommittedineitheronPause()oronSaveInstanceState(Bundle),nothere.Thismethodisusuallyimplementedtofreeresourceslikethreadsthatareassociatedwithanactivity,sothatadestroyedactivitydoesnotleavesuchthingsaroundwhiletherestofitsapplicationisstillrunning.Therearesituationswherethesystemwillsimplykilltheactivity'shostingprocesswithoutcallingthismethod(oranyothers)init,soitshouldnotbeusedtodothingsthatareintendedtoremainaroundaftertheprocessgoesaway. Derivedclassesmustcallthroughtothesuperclass'simplementationofthismethod.Iftheydonot,anexceptionwillbethrown.
希望本文所述对大家Android程序设计有所帮助。
热门推荐
1 训练狗狗憋尿
2 狗狗追踪训练
3 狗狗训练要多少钱
5 深圳狗狗训练
6 训练狗狗唤回
7 狗狗叫怎么训练
8 狗狗训练班
10 狗狗社会化训练
11 狗狗叫回训练
12 广州狗狗训练学校
13 狗狗训练躺下
14 狗狗随行训练
15 训练狗狗巡回
16 狗狗要怎么训练
17 狗狗喂食训练
18 训练狗狗躺下