


Detailed explanation of Activity life cycle in Android_PHP tutorial
Detailed explanation of Activity life cycle in Android
Software and hardware environment
- Macbook Pro MGX 72
- Android Studio 1.3.2
- Genymotion Simulator
Preface
In Android, there are four major development components, which are the basis of Android programming, and Activity is the first and top priority. Heavy. Today we will learn about the life cycle of Activity.
What is Activity?
Activity is the most important component in Android development. Almost all interactive operations are performed in Activity. It is mainly responsible for creating a window. In this window, you can add the UI controls you need by calling the setContentView function. Show it. Let’s first look at an activity life cycle diagram provided by the Android API. If you don’t understand it at first, you can read the entire blog post and then look back to deepen your understanding.
Several important callback functions
The following Activity methods show the complete life cycle of the Activity. When the status of the Activity changes, you can Override these methods to implement certain functionality.
<code class="none" style="-webkit-print-color-adjust:exact;margin:0px;padding:0px;border:none;border-radius:3px;background-color:transparent;"> public class Activity extends ApplicationContext { protected void onCreate(Bundle savedInstanceState); protected void onStart(); protected void onRestart(); protected void onResume(); protected void onPause(); protected void onStop(); protected void onDestroy();}</code>
onCreate
is called when the activity is created for the first time. The creation of views and initialization of data are all performed here. If you are sharp-eyed, you may have discovered that there is a Bundle savedInstanceState parameter in the onCreate method, which will save the previous state of the activity, which is very useful.
onStart
will be called after the onCreate method
onResume
会在onStart方法后调用。activity是使用栈结构来管理的,此时activity处于栈顶。
onRestart
被stop的activity重新启动时调用此函数,后面会紧跟onResume。
onPause
当有新的activity进入栈顶,即当前activity被迫到后台运行,onPause就会被调用。
onStop
会在onPause方法后调用,此时activity对于用户来讲,已经是不可见的了(Invisible)。从栈的角度来说,就是有新的activity压栈,或者已经存在的activity回到了栈顶。
onDestroy
这是生命周期中的最后一个函数。一般情况下activity已经完成(调用finish函数)或者系统为了回收资源主动销毁activity时,onDestroy才会被调用,可以通过isFinishing()方法来区分这2种情况。
综上,从onCreate开始到onDestroy结束,称为activity的一个完整生命周期。这里还有2个概念需要区别一下。
<code class="none" style="-webkit-print-color-adjust:exact;margin:0px;padding:0px;border:none;border-radius:3px;background-color:transparent;">1. 可见的(Visible,从onStart到onStop,这里的可见,不仅仅是在屏幕上可见)2. 前台运行(Foreground,从onResume到onPause)</code>
为了弄明白这些回调函数在各种情况下的调用顺序,我们新建个工程,名叫ActivityLifecycle,在这些回调函数中加些打印,如下
<code class="none" style="-webkit-print-color-adjust:exact;margin:0px;padding:0px;border:none;border-radius:3px;background-color:transparent;">@Overrideprotected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); editText = (EditText)findViewById(R.id.edittext); Log.d(TAG,"=== onCreate ===");}@Overrideprotected void onStart() { super.onStart(); Log.d(TAG,"=== onStart ===");}@Overrideprotected void onResume() { super.onResume(); Log.d(TAG, "=== onResume ===");}@Overrideprotected void onPause() { super.onPause(); Log.d(TAG, "=== onPause ===");}@Overrideprotected void onRestart() { super.onRestart(); Log.d(TAG, "=== onRestart ===");}@Overrideprotected void onStop() { super.onStop(); Log.d(TAG, "=== onStop ===");}@Overrideprotected void onDestroy() { super.onDestroy(); Log.d(TAG, "=== onDestroy ===");}</code>
运行一下程序,从Logcat中可以看到
说明了一个Activity从创建到显示出来需要执行onCreate-->onStart-->onResume三个方法。
While the App is running, if we want to open other Apps, we usually press the Home button to exit. What is the callback like at this time? Look at the picture below:
executes onPause-->onStop, indicating that the Activity has not been destroyed, but has been overwritten by other activities and placed in the background to run. , this situation is the same as when an emergency occurs (such as an incoming call or an App being installed), and when the emergency ends, the Activity will execute onRestart-->onStart-->onResume, and the entire process will be printed. As shown below
When the App is running, if the current Activity is the last Activity, when we press the Back key, the program will end. At this time, the three methods onPause-->onStop-->onDestroy will be executed one after another, as shown below
Next, modify the project slightly and add the second Activity. Called SecondActivity, enter SecondActivity by clicking a button on MainActivity. At this time, if you press the Back key, SecondActivity will execute onPause-->onStop-->onDestroy, and MainActivity will execute onRestart-->onStart- ->onResume, as shown below
onSaveInstanceState and onRestoreInstanceState
There is a concept here, which is not mentioned above. After the onPause and onStop methods are called, the activity process may be killed at any time, so data saving operations should be performed in the onPause method to avoid data loss. The onSaveInstanceState method also performs a similar function, and the data is saved in the given bundle. Because onSaveInstanceState is not an activity life cycle function, the Android API recommends saving data in the onPause method.
Switch between horizontal and vertical screens
No processing is done. Switch between horizontal and vertical screens and look at the print. You can find that the activity is first destroyed and then re-created
In order to solve the above problems, there are generally several methods
- Prohibit switching between horizontal and vertical screens (limited to horizontal or vertical screens, which is rogue and not recommended)
- Independent layouts for horizontal and vertical screens (Create 2 folders layout-land and layout-port, the corresponding xml files remain unchanged)
- Prevent activity reloading (add android:configChanges="keyboardHidden|orientation" to AndroidManifest.xml, and reload Write onConfigurationChanged method)
Source code download
http://download.csdn.net/detail/djstavav/9147793
References
1. http://developer.android.com/intl/zh-cn/reference/android/app/Activity.html
2. http://developer.android.com/guide/topics/manifest/activity- element.html
3. http://developer.android.com/guide/topics/resources/runtime-changes.html

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



In recent days, Ice Universe has been steadily revealing details about the Galaxy S25 Ultra, which is widely believed to be Samsung's next flagship smartphone. Among other things, the leaker claimed that Samsung only plans to bring one camera upgrade

OnLeaks has now partnered with Android Headlines to provide a first look at the Galaxy S25 Ultra, a few days after a failed attempt to generate upwards of $4,000 from his X (formerly Twitter) followers. For context, the render images embedded below h

Alongside announcing two new smartphones, TCL has also announced a new Android tablet called the NXTPAPER 14, and its massive screen size is one of its selling points. The NXTPAPER 14 features version 3.0 of TCL's signature brand of matte LCD panels

In recent days, Ice Universe has been steadily revealing details about the Galaxy S25 Ultra, which is widely believed to be Samsung's next flagship smartphone. Among other things, the leaker claimed that Samsung only plans to bring one camera upgrade

The Vivo Y300 Pro just got fully revealed, and it's one of the slimmest mid-range Android phones with a large battery. To be exact, the smartphone is only 7.69 mm thick but features a 6,500 mAh battery. This is the same capacity as the recently launc

Samsung has not offered any hints yet about when it will update its Fan Edition (FE) smartphone series. As it stands, the Galaxy S23 FE remains the company's most recent edition, having been presented at the start of October 2023. However, plenty of

The Redmi Note 14 Pro Plus is now official as a direct successor to last year'sRedmi Note 13 Pro Plus(curr. $375 on Amazon). As expected, the Redmi Note 14 Pro Plus heads up the Redmi Note 14 series alongside theRedmi Note 14and Redmi Note 14 Pro. Li

Motorola has released countless devices this year, although only two of them are foldables. For context, while most of the world has received the pair as the Razr 50 and Razr 50 Ultra, Motorola offers them in North America as the Razr 2024 and Razr 2
