开发者

onDestroy for making data persistent and sync with the server

I have a little problem to detect when the application is finished. I need to do some actio开发者_如何学编程ns onDestroy like save the parameters into the database and make a final connection to the server.

The problem is that if I put the code in onDestroy its is called when the orientation changes for example. Putting

android:configChanges="orientation|keyboardHidden"

in the manifest for that activity the landscape/portrait layouts don't swap. And adding

@Override
public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);
    setContentView(R.layout.main);
}

Changes the layouts but the buttons and labels do not get the onClickListeners and the text labels correctly. How can I solve that? Thanks


The problem is that your layout items aren't initialized again because you're initializing them in your onCreate() function, and then you're disrupting them with a new layout in onConfigurationChanged().

One option is to move the initialization to a new function that gets called from both onCreate() and onConfigurationChanged().

Another option is to use the android:onclick="" (and related) attributes in your layout.

The option I would choose is different though. I would allow Android to manage orientation (and to call onDestroy()) and in onDestroy() I would install an Alarm for, say, 10 seconds (which I imagine is plenty of time to have onCreate() called again). In onCreate() I would cancel the alarm. When the alarm fires, I would perform my save actions.


Declare buttons and labels as class variable.


setContentView recreates your view, so you must rebind your data. the best approach would be a function called both from onCreate() and onConfigurationChanged(), with layout creation and bindings.


If you don't want to anything to happen when orientation changes occur, than you should not re-setContentView(). Basically you are telling your app: "DO NOTHING WHEN ORIENTATION CHANGES". So, remove the setContentView inside the onConfigurationChanged() or test for which orientation currently is active and then load desired layout resources.

When orientation changes onDestroy() is called because the changes restart your entire activity.

Read more here: http://developer.android.com/guide/practices/screens_support.html#qualifiers http://developer.android.com/guide/topics/resources/providing-resources.html

Orientation testing: Setting the background of an Activity


Could you do that stuff in overriden finish() of the activity?

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜