Android life cycle which event fired only once during the life cycle?

这一生的挚爱 提交于 2019-12-04 15:20:00

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"

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.

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();
        }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!