我也试试老外写博客= =

怎么防止程序后台运行长时间后切换回来导致application里的value被清空而crash。

 

1. Scenario

You have a customize Application (named MyApplication). and you initialize some parameters in MyApplication. When you press 'Home' , your app will be suspended by system . If your memory is not enough, the system will kill your app (include MyApplication). In this case ,  When you switch back to your app . if you access the parameter in MyApplication , the app crashed .

2. How to reproduce this bug manually.

You may not realize this before until the crash log from Umeng or HockeyApp , but you don't know when does this happen , only thing you can do is that wish user don't suspend your app or exit app when they want to brower other apps .

but you can reproduce it .

2.a) run your app through Eclipse , go to the Activity which may access the parameter in MyApplication.

2.b) click 'Home' , suspend your app.

2.c) go to DDMS , choose your process (com.stay.test) ,and stop it .

2.d) now , long press 'Home' or press 'Menu' to resume your app .

2.e) app crash

3.How to resolve

3.a) if you have a good programming style. and you have customized Activity as a super class . like BaseActivity , BaseFragmentActivity. And also you know Activity's lifecircle very clear , you may have a SingleTask Activity always on the bottom of activity stack. In this case , this bug can easily be fixed , just like how to exit app in any Activity

3.b) Well , if your code is not like that , pls change your frame , if not , you will find it hard to resovle bugs when the app became bigger.

3.c) set a flag in MyApplication , to represent your app's state , (-1 default , 0 logout ,1 login)

3.d) in BaseActivity or BaseFragment , override onCreate(Bundle savedInstanceState).

check the flag in MyApplication ,

if is -1 , you should exit app and enter app just like user first to use your app . and the parameters in MyApplication would be initialized in correct workflow.

how to exit? simple .

this will jump to the Activity which is SingleTask .  and with flag 'clear top'. all the activities exclude 'single task' in stack will be removed , and the 'single task' would be brought to top of stack . in this case , if you call finish() in 'single task' activity , you will exit app. cause the 'single task' is already exist , so it would not call onCreate(Bundle savedInstanceState), it will call onNewIntent(Intent intent).

4.Check if this bug is fixed , you should test all activities you have , and make sure it is fixed . it may have different case , and you need to give a special solution .

 

p.s.

解决方案已经写的很明白,概不提供额外解释与说明,如果不能解决,请支付酬劳让我提供服务。(源码和讲解)

posted on 2013-06-06 17:37  stay  阅读(912)  评论(2编辑  收藏  举报