开发者

Application lifecycle. How to run something only when application starts

开发者 https://www.devze.com 2022-12-24 15:48 出处:网络
I have a dialog popup to indicate how long I want an activity to run. Seems simple enough, but its difficult to determine when the activity is really starting.

I have a dialog popup to indicate how long I want an activity to run. Seems simple enough, but its difficult to determine when the activity is really starting. If the user opens the keyboard on a G1 and thereby goes into landscape, that reruns the activities onCreate method.

I can't have a static for the class or even create an application class, because I can't determine when the 'application' goes away. Even after 开发者_StackOverflow中文版destroying the only activity, the application is apparently still alive.

Is there a way to determine that onCreate has been called because of the keyboard being extended or landscape mode invoked?

Thanks


In onSaveInstanceState you could store a flag indicating if it had run. If the app was being restored then in onCreate(Bundle savedInstanceState), the savedInstanceState will have the variable so you could check if savedInstanceState != null and saveInstanceState.get("restoring") != null then don't show the dialog.


I tried creating an application subclass, but still I could not determine when it would go away.

I tried another approach. I added in the manifest within the activity,

android:configChanges="orientation|keyboardHidden"

Then within the activity I added,

public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);
}

This results in my onCreate method NOT being called when the orientation changes or the keyboard is hidden. I'm not sure why my view still looks correct in either case, but it works great. In fact it even handle text typed into the displayed dialog. The text is maintained when the orientation is changed.


Is there a way to determine that onCreate has been called because of the keyboard being extended or landscape mode invoked?

There is a way to:
1. Check if the keyboard is being extended
2. a way to check the current orientation (landscape or portrait)

Determining whether onCreate() has been called or not will require some work on your part. For instance, you can have a variable to flag completion of onCreate() and save it in Activity's state Bundle.

You can put a check in onCreate() to determine if this is a first run or a restart due to Configuration changes, by making some sense out of values from 1,2 and the flag.

This is just a suggestion; better solutions might exist

0

精彩评论

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