I have read some blogs and visited some site. I want to know which event fired only one time during the life cycle. After reading blogs I realize that onCreate()
method is fired only once during the life cycle. I don't know I am right or wrong. Now my problem is that I want to fired any event which fired one time only if I change the landscape orientation or portrait orientation than this event not fired means after starting activity if user change the orientation than event not fired. I want to know which event fired only one time after starting Activity. this onCreate()
问题:
回答1:
onCreate
and onDestroy
id fired only once.
onCreate:
Called when the activity is first created. This is where you should do all of your normal static set up: create views, bind data to lists, etc...
onDestroy
: The final call you receive before your activity is destroyed. This can happen either because the activity is finishing.
so, put your event code in onCreate.(but its depend on your requirement what you are trying to do your code may be change)
Activity Flow:
first onCreate
is called --> Next --> onStart
--> onResume
--> your Activity is Running is show you your layout. (whatever you have put in your layout.xml)
now if you Press HOME Button then its goes to --> onPause
--> onStop
. (Activity is not Destroy its running in background). now again open Activity its go to --> onRestart
--> onStart
--> onResumme
(activity is running again).
now if you Press Back Button then --> onPause
--> onStop
--> onDestroy
.
Edited:
to stop restart activity when orientation change use
android:configChanges="orientation|keyboardHidden"
in android manifest file.
<activity android:name=".MyActivity"
android:configChanges="orientation|keyboardHidden"
android:label="@string/app_name">
if you developing for API level 13 or higher you must use
android:configChanges="orientation|screenSize"
回答2:
Make a dummy application, override onCreate
, onStart
, onResume
, onPause
, onDestroy
, onRestart
put Log.d("MYAPP", "onXXX called")
in there and see for yourself what and in which order gets called.
This way you learn things practical way once and for all.
回答3:
You can make use of preferences in onCreate().
SharedPreferences prefs = PreferenceManager
.getDefaultSharedPreferences(this);
if (!prefs.getBoolean("firstTime", false)) {
// run your one time code
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean("firstTime", true);
editor.commit();
}