开发者

Activity lifecycle related issue

I'm using a CountDownTimer's onTick(long l) function to check some conditions and if they are satisfied then I call an activity's function to perform some UI related tasks. However I'm wondering if it is possible that while the activity is destroyed and rec开发者_高级运维reated due to an orientation change, the onTick() to be run, and possible to call for the function in my activity, activity that might not yet be created?

If so any ideas on how this could be corrected ?


I would use AlarmManager and a BroadcastReceiver to handle repeating stuff.

Also read about Listening for and broadcasting global messages and setting alarms Some other tutorials about Android AlarmManager

But this will give you the best answers possible, just read about alarmmanager tutorial


Using a Service might be a good choice. These are not created and destroyed in the same way that Activities are. A Service will continue to run when your Activity dies (except in some exceptional circumstances). Therefore, if you want to continue your timer across Activity instances, try using a Service.

A friendly warning: Services are more easily killed than Activities when a device is low on memory (it's better to removes something the user can see than something the user cannot see). Assuming you want this timer to work from its inception until you explicitly kill it, then it would be best to keep resurrecting the Service whenever it is removed by the operating system. You do this by making its onStartCommand method return the START_REDILIVER_INTENT constant. Although this does not guarantee that the Service will remain alive for this entire interval, it does mean that it will come back eventually. If your application doesn't consume too much memory, you shouldn't have to worry about this. If it does, then you'll need to be creative with your use of a timer.


Another idea: handle the screen orientation change yourself to prevent your application from being reset. This approach has its share of negative consequences, as stated on the Android developer site:

Handling the configuration change yourself can make it much more difficult to use alternative resources, because the system does not automatically apply them for you. This technique should be considered a last resort and is not recommended for most applications.

Depending on your application, this might be OK. Either way, it's a relatively easy change to your manifest file, so you could give it a shot and see what happens.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜