服务器之家:专注于VPS、云服务器配置技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - Android - Android编程中activity的完整生命周期实例详解

Android编程中activity的完整生命周期实例详解

2021-04-23 15:13octobershiner Android

这篇文章主要介绍了Android编程中activity的完整生命周期,结合实例形式较为详细的分析了Android编程中activity的原理与具体用法,需要的朋友可以参考下

本文实例分析了android编程中activity的完整生命周期。分享给大家供大家参考,具体如下:

android中 activity有自己的生命周期,对这些知识的学习可以帮助我们在今后写程序的时候,更好的理解其中遇到的一些错误。这篇文章很长,希望不要耽误大家的时间~

今天不会涉及太多关于activity栈的东西,主要说activity自身的生命周期

区分几个概念

1 activity 官方解释为 “an activity is an application component that provides a screen with which users can interact in order to do something, such as dial the  phone, take a photo, send an email, or view a map. each activity is given a window in which to draw its user interface. ”也就是用户用来交互的每一个窗口,用户当前正在进行的一个操作。

2 back-stack  用户通过触摸程序会通过application launcher来启动一个activity a,启动的activity a会被压入栈顶,如果当前的activity a再启动一个新的activity b,那么此时a调用onstop函数,系统会维护这个activity信息.当用户按下back键的时候,back stack会进行一个pop的操作,并且调用a的onresume()  具体的进出栈细节,以后会详细介绍。

3 tasks  当用户处于某个activi提: activity a在名称为"taskone应用ty的时候,按下home键用户返回到launcher,此时,如果用户再触摸新的应用,则新建一个task,一个back stack就代表一个task.不同程序的activity可以压入同一个栈中,也就是说可以组成一个task,比如你的程序启动了一个系统自带的发短信的activity,给用户的感觉就是发短信好像是你的程序中的一个功能一样。

注释:以上的行为均为系统的默认设置,有两种方式可以改变activity的行为,加入a启动b,一是在b的manifest设置中,改变行为,另一种是在activity发起的intent中指定要启动的activity设置,其中intent的优先级要高于manifest.xml文件,并且有些mode在并不是同时都存在于两种方式中

android的生命周期包括  oncreate onstart onrestart onresume onpause onstop ondestroy ,activity在声明周期中会调用以上方法来执行不同状态对应的操作,下面介绍各个方法的调用时间

oncreate()     次状态下activity不可被终结
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. this method also provides you with a bundle containing the activity's previously frozen state, if there was one.

always followed by onstart().
//当activity第一次被创建的时候调用。你应该在这个方法里进行所有的静态创建,创建views,(通过setcontnetview方法)向lists绑定数据等等。如果存在保存的状态的话,该方法也提供给你一个包含activity最近状态的一个bundle。onstart方法总是在此方法之后调用

onrestart()    次状态下activity不可被终结
called after your activity has been stopped, prior to it being started again.
always followed by onstart()
//在你的activity停止后被调用,在重新开始之前调用

onresume()    次状态下activity不可被终结
called when the activity will start interacting with the user. at this point your activity is at the top of the activity stack, with user input going to it.
always followed by onpause().
//当activity将被启动与用户交互的时候被调用。此刻你的activity处于activity栈的顶端,用于用户输入,永远///在onpause之后被调用

onpause()    次状态下activity不可被终结 ,android honeycomb系统除外
called when the system is about to start resuming a previous activity. this is typically used to commit unsaved changes to persistent data, stop animations and other things that may be consuming cpu, etc. implementations of this method must be very quick because the next activity will not be resumed until this method returns.
followed by either onresume() if the activity returns back to the front, or onstop() if it becomes invisible to the user.

//当系统即将重新开始以前的activity的时候被调用(不懂,自己的理解是:当当前activity要启动新的activity的时候被调用),典型的应用是用来将还未保存的数据提交到当前的数据,(意思就是保存数据更新),停止animations和其他可能耗费cpu的操作。对此方法的实现必须快速因为下个activity直到此方法返回才会被重新开始。

当activity从back(翻译后台不合适)转到front(与用户交互的状态)的时候,onresume方法会在onpause方法之后被调用

当activity变为不可见的时候,onstop方法会在onpause之后被调用

onstop()     次状态下activity可以被终结
called when the activity is no longer visible to the user, because another activity has been resumed and is covering this one. this may happen either because a new activity is being started, an existing one is being brought in front of this one, or this one is being destroyed.
followed by either onrestart() if this activity is coming back to interact with the user, or ondestroy() if this activity is going away.

//当activity对用户不再可见时被调用,因为另一个activity已经重新开始并且覆盖了当前activity(在栈中)。当有新的activity被启动,或者一个存在的activity重新回到前台状态,又或者当前的activity将被销毁。如果activity要返回前台和用户进行交互则在此方法后调用onreatart方法,如果当前activity要消亡,则ondestroy方法将在此方法后被调用

ondestroy()     次状态下activity可以被终结
the final call you receive before your activity is destroyed. this can happen either because the activity is finishing (someone called finish() on it, or because the system is temporarily destroying this instance of the activity to save space. you can distinguish between these two scenarios with the isfinishing() method.

这是当你的activity被消亡时接收到的最后一个方法。调用此方法有两种情形:一是 activity将要完成,可通过调用finish方法实现。而是系统销毁activity的实例来释放空间。可以使用isfinish方法来区别两种情形。这个方法常用在onpause方法中,来判断activity是暂停还是将终止。后面的demo将会演示这个功能。

下图是官网的一个生命周期的演示

Android编程中activity的完整生命周期实例详解

好了 看一下我写的一个演示的例子吧,

mainfest.xml

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
   package="uni.activity"
   android:versioncode="1"
   android:versionname="1.0">
  <uses-sdk android:minsdkversion="7" />
  <application android:icon="@drawable/icon" android:label="@string/app_name">
    <activity android:name=".activitydemoactivity"
         android:label="@string/app_name">
      <intent-filter>
        <action android:name="android.intent.action.main" />
        <category android:name="android.intent.category.launcher" />
      </intent-filter>
    </activity>
    <activity android:name=".activity01"
         android:label="@string/app_name">
    </activity>
  </application>
</manifest>

布局文件 main.xml

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<?xml version="1.0" encoding="utf-8"?>
<linearlayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="vertical"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent"
  >
<textview 
  android:layout_width="fill_parent"
  android:layout_height="wrap_content"
  android:text="@string/hello"
  />
 <button 
  android:id="@+id/button_a"
  android:text="go to activity 2"
  android:layout_width="fill_parent"
  android:layout_height="wrap_content"
  />
</linearlayout>

activity01.xml

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<?xml version="1.0" encoding="utf-8"?>
<linearlayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="vertical"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent"
  >
<textview 
  android:layout_width="fill_parent"
  android:layout_height="wrap_content"
  android:text="@string/hello"
  />
 <button 
  android:id="@+id/button_a"
  android:text="go to activity 2"
  android:layout_width="fill_parent"
  android:layout_height="wrap_content"
  />
</linearlayout>

string.xml

?
1
2
3
4
5
6
<?xml version="1.0" encoding="utf-8"?>
<resources>
  <string name="hello">hello world, activitydemoactivity!</string>
  <string name="app_name">activitydemo</string>
  <string name="activity01">this is activity 01</string>
</resources>

activitydemoactivity.java

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
/*
 * @author octobershiner
 * 2011 07 29
 * se.hit
 * 演示完整的activity的声明周期,以及isfinish方法的调用
 * 此activity为程序入口activity
 * */
package uni.activity;
import android.app.activity;
import android.content.intent;
import android.os.bundle;
import android.util.log;
import android.view.view;
import android.view.view.onclicklistener;
import android.widget.button;
public class activitydemoactivity extends activity {
  /** called when the activity is first created. */
  private static final string tag = "demo";
  private button button_a;
  @override
  public void oncreate(bundle savedinstancestate) {
    super.oncreate(savedinstancestate);
    setcontentview(r.layout.main);
    button_a = (button)this.findviewbyid(r.id.button_a);
    button_a.setonclicklistener(new mybuttonlistener());
  }
  private class mybuttonlistener implements onclicklistener{
    @override
    public void onclick(view v) {
      // todo auto-generated method stub
      intent intent = new intent();
      intent.setclass(activitydemoactivity.this, activity01.class);
      activitydemoactivity.this.startactivity(intent);
      //感兴趣的朋友可以取消下面的代码注释,来测试finish方法的使用,会发现第一个activity会被强制终止
      //activitydemoactivity.this.finish();
    }
  };
  protected void onstart(){
    super.onstart();
    log.i(tag, "the activitydemo state---->onstart");
  }
  protected void onrestart(){
    super.onrestart();
    log.i(tag, "the activitydemo state---->onreatart");
  }
  protected void onresume(){
    super.onresume();
    log.i(tag, "the activitydemo state---->onresume");
  }
  protected void onpause(){
    super.onpause();
    //调用isfinishing方法,判断activity是否要销毁
    log.i(tag, "the activitydemo state---->onpause");
    if(isfinishing()){
      log.w(tag, "the activitydemo will be destroyed!");
    }else{
      log.w(tag, "the activitydemo is just pausing!");
    }
  }
  protected void onstop(){
    super.onstop();
    log.i(tag, "the activitydemo state---->onstop");
  }
  protected void ondestroy(){
    super.ondestroy();
    log.i(tag, "the activitydemo state---->ondestroy");
  }
}

activity01.java

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
/*
 * @author octobershiner
 * 2011 07 29
 * se.hit
 * 演示完整的activity的声明周期,以及isfinish方法的调用
 * 此activity可由activitydemoactivity启动
 * */
package uni.activity;
import android.app.activity;
import android.os.bundle;
import android.util.log;
public class activity01 extends activity{
  private static final string tag = "demo";
  @override
  protected void oncreate(bundle savedinstancestate) {
    // todo auto-generated method stub
    super.oncreate(savedinstancestate);
    setcontentview(r.layout.activity01);
    log.d(tag, "the activity01 state---->onstart");
  }
   protected void onstart(){
      super.onstart();
      log.d(tag, "the activity01 state---->onstart");
    }
    protected void onrestart(){
      super.onrestart();
      log.d(tag, "the activity01 state---->onreatart");
    }
    protected void onresume(){
      super.onresume();
      log.d(tag, "the activity01 state---->onresume");
    }
    protected void onpause(){
      super.onpause();
      log.d(tag, "the activity01 state---->onpause");
      //调用isfinishing方法,判断activity是否要销毁
      if(isfinishing()){
        log.w(tag, "the activity01 will be destroyed!");
      }else{
        log.w(tag, "the activity01 is just pausing!");
      }
    }
    protected void onstop(){
      super.onstop();
      log.d(tag, "the activity01 state---->onstop");
    }
    protected void ondestroy(){
      super.ondestroy();
      log.d(tag, "the activity01 state---->ondestroy");
    }
}

下面是演示的结果,

操作过程是:启动activitydemoactivity

Android编程中activity的完整生命周期实例详解

然后单击按钮进入activity01

Android编程中activity的完整生命周期实例详解

(可见activity先暂停并且不会被释放,实际是个新activity压栈过程,然后新的activity开始,应该是oncreate然后onstart,我打印语句写错了,细心朋友应该看到了,当旧的activity不可见时,调用其onstop方法)

再按返回键回到activitydemoactivity

Android编程中activity的完整生命周期实例详解

(返回后,处于栈顶的activity01会执行弹栈操作,显示将会被destroy)

再按返回键 回到桌面

Android编程中activity的完整生命周期实例详解

其实并不复杂的东邪写的有些长了,但是基本上的显示了activity的完整的生命周期。

希望本文所述对大家android程序设计有所帮助。

延伸 · 阅读

精彩推荐
  • Android汇总Android视频录制中常见问题

    汇总Android视频录制中常见问题

    这篇文章主要汇总了Android视频录制中常见问题,帮助大家更好地解决Android视频录制中常见的问题,需要的朋友可以参考下...

    yh_thu5192021-04-28
  • AndroidAndroid实现Service获取当前位置(GPS+基站)的方法

    Android实现Service获取当前位置(GPS+基站)的方法

    这篇文章主要介绍了Android实现Service获取当前位置(GPS+基站)的方法,较为详细的分析了Service基于GPS位置的技巧,具有一定参考借鉴价值,需要的朋友可以参考下...

    Ruthless8342021-03-31
  • AndroidAndroid界面效果UI开发资料汇总(附资料包)

    Android界面效果UI开发资料汇总(附资料包)

    android ui界面设计,友好的界面会提高用户体验度;同时也增强了android ui界面设计的难度,本文提供了一些常用开发资料(有下载哦)感兴趣的朋友可以了解下...

    Android开发网4672021-01-03
  • AndroidAndroid编程解析XML方法详解(SAX,DOM与PULL)

    Android编程解析XML方法详解(SAX,DOM与PULL)

    这篇文章主要介绍了Android编程解析XML方法,结合实例形式详细分析了Android解析XML文件的常用方法与相关实现技巧,需要的朋友可以参考下...

    liuhe68810052021-05-03
  • AndroidAndroid CardView+ViewPager实现ViewPager翻页动画的方法

    Android CardView+ViewPager实现ViewPager翻页动画的方法

    本篇文章主要介绍了Android CardView+ViewPager实现ViewPager翻页动画的方法,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧...

    Abby代黎明9602022-03-02
  • AndroidAndroid实现固定屏幕显示的方法

    Android实现固定屏幕显示的方法

    这篇文章主要介绍了Android实现固定屏幕显示的方法,实例分析了Android屏幕固定显示所涉及的相关技巧,具有一定参考借鉴价值,需要的朋友可以参考下...

    鉴客6192021-03-27
  • AndroidAndroid程序设计之AIDL实例详解

    Android程序设计之AIDL实例详解

    这篇文章主要介绍了Android程序设计的AIDL,以一个完整实例的形式较为详细的讲述了AIDL的原理及实现方法,需要的朋友可以参考下...

    Android开发网4642021-03-09
  • AndroidAndroid中AsyncTask详细介绍

    Android中AsyncTask详细介绍

    这篇文章主要介绍了Android中AsyncTask详细介绍,AsyncTask是一个很常用的API,尤其异步处理数据并将数据应用到视图的操作场合,需要的朋友可以参考下...

    Android开发网7452021-03-11