Activity之生命周期

本文详细解析了Android Activity的三种基本状态及生命周期流程,包括如何启动、暂停、重启以及应对屏幕旋转的机制。同时介绍了Activity在不同状态下的回调方法及其作用,为开发者提供了一个全面的理解框架。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Activity是Android四大组件中,和用户直接交互的组件,直接影响到用户体验,接下来首先分析一下Activity的生命周期,


 

Activity有三种基本状态:

  1. Active:处于屏幕前景(当前task的栈顶Activity处于Active状态),同一时刻只能有一个Activity处于Active状态;
  2. Paused状态:处于背景画面画面状态,失去了焦点,但依然是活动状态;
  3. stopped:不可见,但依然保持所有的状态和内存信息。

Activity的生命周期大致可分为三组:

  • The entire lifetime of an activity happens between the first call toonCreate() through to a single final call to onDestroy().
  • The visible lifetime of an activity happens between a call toonStart() until a corresponding call to onStop().

  • The foreground lifetime of an activity happens between a call to onResume() until a corresponding call toonPause().

Activity有三种基本状态:

1,Active,处于屏幕前景(当前task的栈顶Acitivity处于active状态),同一时刻只能有一个activity处于active状态;

2,Paused状态:处于背景画面状态,失去了焦点,但依然处于活动状态,并且是可见的,

3,Stopped,不可见,但保持所有的状态和内存信息。

1,启动Activity时:首先调用onCreate()方法,接着调用 onStart()方法,然后是onResume()(接着onWindowFocusChanged()会被调用)activity获得窗口焦点,之后Activity进入正常的运行状态,

2,当前Activity被其他Activity覆盖或者锁屏时,首先调用其onPause()方法,然后是onSaveInstanceState()方法,接着调用onStop()方法,接着onWindowFocusChanged()会被调。

3, 解锁时或者重新回到Activity时, onRestart--->onStart()--->onResume()--->onWindowFocusChanged.

    按Home键:onPause()--->onWindowFocusChanged()--->onSaveInstanceState()--->onStop().

    锁屏时:   onPause()--->onSaveInstanceState()--->onStop()--->onWindowFocusChanged()

4,如果Activity处于被覆盖或者后台不可见状态,如果系统内存紧张,Activity会被直接kill掉,重启时,走第一种情况 。当屏幕旋转时,Activity会被kill掉,并且重新创建.

5,用户退出当前Activity:系统先调用onPause方法,然后调用onStop方法,最后调用onDestory方法,结束当前Activity。

旋转屏幕:

布局文件:main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="${packageName}.${activityClass}" >


    <TextView
        android:id="@+id/text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />
    <Button 
        android:id="@+id/btn"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="click"
        android:layout_below="@id/text"
        />
    <EditText 
        android:id="@+id/edit"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/btn"/>


</RelativeLayout>



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值