Table of Contents
Detailed explanation of Activity life cycle in Android
Software and hardware environment
Preface
What is Activity?
Several important callback functions
onCreate
onStart
onResume
onRestart
onPause
onStop
onDestroy
onSaveInstanceState and onRestoreInstanceState
Switch between horizontal and vertical screens
Source code download
References
Home Backend Development PHP Tutorial Detailed explanation of Activity life cycle in Android_PHP tutorial

Detailed explanation of Activity life cycle in Android_PHP tutorial

Jul 12, 2016 am 09:03 AM
android

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.

Detailed explanation of Activity life cycle in Android_PHP tutorial

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>
Copy after login

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>
Copy after login

为了弄明白这些回调函数在各种情况下的调用顺序,我们新建个工程,名叫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>
Copy after login

运行一下程序,从Logcat中可以看到

Detailed explanation of Activity life cycle in Android_PHP tutorial

说明了一个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:

Detailed explanation of Activity life cycle in Android_PHP tutorial

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

Detailed explanation of Activity life cycle in Android_PHP tutorial

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

Detailed explanation of Activity life cycle in Android_PHP tutorial

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

Detailed explanation of Activity life cycle in Android_PHP tutorial

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

Detailed explanation of Activity life cycle in Android_PHP tutorial

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

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/1077807.htmlTechArticleDetailed explanation of the Activity life cycle in Android Software and hardware environment Macbook Pro MGX 72 Android Studio 1.3.2 Genymotion emulator Preface in In Android, there are four major development components, which are Android programming...
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

New report delivers damning assessment of rumoured Samsung Galaxy S25, Galaxy S25 Plus and Galaxy S25 Ultra camera upgrades New report delivers damning assessment of rumoured Samsung Galaxy S25, Galaxy S25 Plus and Galaxy S25 Ultra camera upgrades Sep 12, 2024 pm 12:23 PM

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

Samsung Galaxy S25 Ultra leaks in first render images with rumoured design changes revealed Samsung Galaxy S25 Ultra leaks in first render images with rumoured design changes revealed Sep 11, 2024 am 06:37 AM

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

IFA 2024 | TCL\'s NXTPAPER 14 won\'t match the Galaxy Tab S10 Ultra in performance, but it nearly matches it in size IFA 2024 | TCL\'s NXTPAPER 14 won\'t match the Galaxy Tab S10 Ultra in performance, but it nearly matches it in size Sep 07, 2024 am 06:35 AM

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

New report delivers damning assessment of rumoured Samsung Galaxy S25, Galaxy S25 Plus and Galaxy S25 Ultra camera upgrades New report delivers damning assessment of rumoured Samsung Galaxy S25, Galaxy S25 Plus and Galaxy S25 Ultra camera upgrades Sep 12, 2024 pm 12:22 PM

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

Vivo Y300 Pro packs 6,500 mAh battery in a slim 7.69 mm body Vivo Y300 Pro packs 6,500 mAh battery in a slim 7.69 mm body Sep 07, 2024 am 06:39 AM

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 Galaxy S24 FE billed to launch for less than expected in four colours and two memory options Samsung Galaxy S24 FE billed to launch for less than expected in four colours and two memory options Sep 12, 2024 pm 09:21 PM

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

Xiaomi Redmi Note 14 Pro Plus arrives as first Qualcomm Snapdragon 7s Gen 3 smartphone with Light Hunter 800 camera Xiaomi Redmi Note 14 Pro Plus arrives as first Qualcomm Snapdragon 7s Gen 3 smartphone with Light Hunter 800 camera Sep 27, 2024 am 06:23 AM

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 Razr 50s shows itself as possible new budget foldable in early leak Motorola Razr 50s shows itself as possible new budget foldable in early leak Sep 07, 2024 am 09:35 AM

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

See all articles