activity 生命周期 http://stackoverflow.com/questions/8515936/android-activity-life-cycle-what-are-all-these-methods-for


331down voteaccepted

See it in Activity Lifecycle (at Android Developers).

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. This method also provides you with a Bundle containing the activity‘s previously frozen state, if there was one. Always followed by onStart().

onRestart():

Called after your activity has been stopped, prior to it being started again. Always followed by onStart()

onStart():

Called when the activity is becoming visible to the user. Followed by onResume() if the activity comes to the foreground, or onStop() if it becomes hidden.

onResume():

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().

onPause ():

Called as part of the activity lifecycle when an activity is going into the background, but has not (yet) been killed. The counterpart to onResume(). When activity B is launched in front of activity A, this callback will be invoked on A. B will not be created until A‘s onPause() returns, so be sure to not do anything lengthy here.

onStop():

Called when you are no longer visible to the user. You will next receive either onRestart(), onDestroy(), or nothing, depending on later user activity.

Note that this method may never be called, in low memory situations where the system does not have enough memory to keep your activity‘s process running after its onPause() method is called.

onDestroy():

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.

When the Activity first time loads the events are called as below:

onCreate()
onStart()
onResume()

When you click on Phone button the Activity goes to the background and the below events are called:

onPause()
onStop()

Exit the phone dialer and the below events will be called:

onRestart()
onStart()
onResume()

When you click the back button OR try to finish() the activity the events are called as below:

onPause()
onStop()
onDestroy()


Activity States

The Android OS uses a priority queue to assist in managing activities running on the device. Based on the state a particular Android activity is in, it will be assigned a certain priority within the OS. This priority system helps Android identify activities that are no longer in use, allowing the OS to reclaim memory and resources. The following diagram illustrates the states an activity can go through, during its lifetime:

These states can be broken into three main groups as follows:

Active or Running - Activities are considered active or running if they are in the foreground, also known as the top of the activity stack. This is considered the highest priority activity in the Android Activity stack, and as such will only be killed by the OS in extreme situations, such as if the activity tries to use more memory than is available on the device as this could cause the UI to become unresponsive.

Paused - When the device goes to sleep, or an activity is still visible but partially hidden by a new, non-full-sized or transparent activity, the activity is considered paused. Paused activities are still alive, that is, they maintain all state and member information, and remain attached to the window manager. This is considered to be the second highest priority activity in the Android Activity stack and, as such, will only be killed by the OS if killing this activity will satisfy the resource requirements needed to keep the Active/Running Activity stable and responsive.

Stopped - Activities that are completely obscured by another activity are considered stopped or in the background. Stopped activities still try to retain their state and member information for as long as possible, but stopped activities are considered to be the lowest priority of the three states and, as such, the OS will kill activities in this state first to satisfy the resource requirements of higher priority activities.

Sample activity to understand the life cycle*

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
public class MainActivity extends Activity {
    String tag = "LifeCycleEvents";
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.main);
       Log.d(tag, "In the onCreate() event");
    }
    public void onStart()
    {
       super.onStart();
       Log.d(tag, "In the onStart() event");
    }
    public void onRestart()
    {
       super.onRestart();
       Log.d(tag, "In the onRestart() event");
    }
    public void onResume()
    {
       super.onResume();
       Log.d(tag, "In the onResume() event");
    }
    public void onPause()
    {
       super.onPause();
       Log.d(tag, "In the onPause() event");
    }
    public void onStop()
    {
       super.onStop();
       Log.d(tag, "In the onStop() event");
    }
    public void onDestroy()
    {
       super.onDestroy();
       Log.d(tag, "In the onDestroy() event");
    }
}

shareimprove this answer

edited Jan 22 ‘14 at 22:19

Peter Mortensen
8,155105691

answered Dec 15 ‘11 at 6:37

Yaqub Ahmad
12.9k1455104

 

    

@Taqub Ahmad Thank you for the explanation.Now i got it :) –  Nav Dec 15 ‘11 at 15:05
    

So if I understood it correctly onStop() is always called after onPause() ? –  Titouan de Bailleul Oct 31 ‘12 at 16:19
3  

NOT always, "onStop(): Called when you are no longer visible to the user" –  Yaqub Ahmad Nov 26 ‘12 at 8:22
    

Is there anything by any chance that gets called before onCreate? –  Aaron Russell Sep 23 ‘13 at 3:31
    

Yes there is - the default constructor (that‘s the one with no parameters). But it has only very limited use for very basic initialization purposes. Usually you should not use it unless you really know what you are doing. And even then you should think twice if there‘s a better way of doing things. –  Mjoellnir Feb 28 at 7:45

show 1 more comment


up vote5down vote

Activity have six states

  • Created
  • Started
  • Resumed
  • Paused
  • Stopped
  • Destoryed

Activity lifecycle have seven methods

  • onCreate()
  • onStart()
  • onResume()
  • onPause()
  • onStopped()
  • onRestart()
  • onDestory()

Situations

  • When open the app

    onCreate() --> onStart() -->  onResume()
  • When back button pressed and exit the app
    onPaused() -- > onStop() --> onDestory()
  • When home button pressed
    onPaused() --> onStop()
  • After pressed home button when again open app from recent task list or clicked on icon
    onRestart() --> onStart() --> onResume()
  • When open app another app from notification bar or open settings
    onPaused() --> onStop()
  • Back button pressed from another app or settings then used can see our app
    onRestart() --> onStart() --> onResume()
  • When any dialog open on screen
    onPause()
  • After dismiss the dialog or back button from dialog
    onResume()
  • Any phone is ringing and user in the app
    onPause() --> onResume()
  • When user pressed phone‘s answer button
    onPause()
  • After call end
    onResume()
  • When phone screen off
    onPaused() --> onStop()
  • Again screen on
    onRestart() --> onStart() --> onResume()

shareimprove this answer

edited Mar 28 at 3:59

answered Feb 28 at 6:42

Arun Kumar
594510

 
add a comment

up vote0down vote

The best Demo Application for understanding Activity Life Cycle is here apk file attached.


shareimprove this answer

answered Oct 20 ‘14 at 14:16

Faakhir
54168

 
add a comment

up vote16down vote

ANDROID LIFE-CYCLE

There are seven methods that manage the life cycle of an Android application:


Answer for what are all these methods for:

Let us take a simple scenario where knowing in what order these methods are called will help us give a clarity why they are used.

  • Suppose you are using a calculator app. Three methods are called in succession to start the app.

onCreate() - - - > onStart() - - - > onResume()

  • When I am using the calculator app, suddenly a call comes the. The calculator activity goes to the background and another activity say. Dealing with the call comes to the foreground, and now two methods are called in succession.

onPause() - - - > onStop()

  • Now say I finish the conversation on the phone, the calculator activity comes to foreground from the background, so three methods are called in succession.

onRestart() - - - > onStart() - - - > onResume()

  • Finally, say I have finished all the tasks in calculator app, and I want to exit the app. Futher two methods are called in succession.

onStop() - - - > onDestroy()


There are four states an activity can possibly exist:

  • Starting State
  • Running State
  • Paused State
  • Stopped state

Starting state involves:

Creating a new Linux process, allocating new memory for the new UI objects, and setting up the whole screen. So most of the work is involved here.

Running state involves:

It is the activity (state) that is currently on the screen. This state alone handles things such as typing on the screen, and touching & clicking buttons.

Paused state involves:

When an activity is not in the foreground and instead it is in the background, then the activity is said to be in paused state.

Stopped state involves:

A stopped activity can only be bought into foreground by restarting it and also it can be destroyed at any point in time.

The activity manager handles all these states in such a way that the user experience and performance is always at its best even in scenarios where the new activity is added to the existing activities


shareimprove this answer

edited Sep 23 ‘14 at 7:37

Martijn Pieters
353k32641840

answered Sep 10 ‘13 at 14:11

Devrath
5,66464671

 
add a comment

up vote5down vote

From the Android Developers page,

onPause():

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.

onStop():

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.

Now suppose there are three Activities and you go from A to B, then onPause of A will be called now from B to C, then onPause of B and onStop of A will be called.

The paused Activity gets a Resume and Stopped gets Restarted.

When you call this.finish(), onPause-onStop-onDestroy will be called. The main thing to remember is: paused Activities get Stopped and a Stopped activity gets Destroyed whenever Android requires memory for other operations.

I hope it‘s clear enough.


shareimprove this answer

edited Jan 22 ‘14 at 22:21

Peter Mortensen
8,155105691

answered Dec 15 ‘11 at 6:25

Masiar
2,990104986

 

    

can we term onPause method as an intermediate stage between the activity starting to loose focus and it finally becoming invisble to the user and the Onstop method as when the activity has become completely invisble to the user –  Nav Dec 15 ‘11 at 6:29 
    

I think it should be like that. –  Masiar Dec 15 ‘11 at 6:31
3  

@Nav Suppose there are 3 Activities and You go from A to B,then onPause of A will be called now from B to C then onPause of B and onStop of A will be called. –  MKJParekh Dec 15 ‘11 at 6:44

add a comment


up vote64down vote

The entire confusion is caused since Google chose non-intuivitive names instead of something as follows:

onCreateAndPrepareToDisplay()   [instead of onCreate() ]
onPrepareToDisplay()            [instead of onRestart() ]
onVisible()                     [instead of onStart() ]
onBeginInteraction()            [instead of onResume() ]
onPauseInteraction()            [instead of onPause() ]
onInvisible()                   [instead of onStop]
onDestroy()                     [no change]

The Activity Diagram can be interpreted as:


shareimprove this answer

edited Mar 10 ‘12 at 23:22

answered Feb 2 ‘12 at 13:35

Nilesh Pawar
1,547610

 

    

Depends. Unless it solves confusion, a long name ain‘t hurt. Eg: onRoutePresentationDisplayChanged() is very much a function from inside Android SDK –  Nilesh Pawar Apr 29 ‘13 at 18:45
    

If we had to type these method names often, the ones from the SDK present a good balance between length and being descriptive enough. However, IDEs have shortcuts to override these things and we don‘t really need to be calling them around, so longer descriptive names as these would have worked just nicely. This is more of a problem to beginners though. –  Daniel Jul 27 ‘13 at 10:46
3  

I personally don‘t find your names extremely more intuitive, plus with Fragments, it doesn‘t really correlate. – Martín Marconcini Aug 2 ‘13 at 21:44
2  

Upvoted. More helpful than the official documentation –  ronnieaka Mar 3 ‘14 at 5:41 
1  

+1 good job, thank you! –  necromancer Aug 5 ‘14 at 3:45

show 3 more comments

时间: 2024-10-21 06:47:53

activity 生命周期 http://stackoverflow.com/questions/8515936/android-activity-life-cycle-what-are-all-these-methods-for的相关文章

Android应用开发(二):Activity生命周期剖析以及如何启动新的Activity或网页

本文讲述组件Activity的相关知识,主要包括如何启动一个Activity.如何打开一个网页,最后解析Activity的生命周期相关知识. 1.如何启动一个Activity (1).新建一个Activity 要启动一个新的Activity,就必须先创建一个新的Activity,Android Studio可以直接创建Activity而不需要一行一行的敲代码,这就是前面所说的采用Android Studio平台的好处之一. 具体代码如下: package edu.fred.hqu.android

Android总结篇系列:Activity生命周期

Android官方文档和其他不少资料都对Activity生命周期进行了详细介绍,在结合资料和项目开发过程中遇到的问题,本文将对Activity生命周期进行一次总结. Activity是由Activity栈进管理,当来到一个新的Activity后,此Activity将被加入到Activity栈顶,之前的Activity位于此Activity底部.Acitivity一般意义上有四种状态: 1.当Activity位于栈顶时,此时正好处于屏幕最前方,此时处于运行状态: 2.当Activity失去了焦点但

Activity生命周期(深入理解)

今天看到一篇大神总结Activity的文章,内容甚为详细,特此转载http://www.cnblogs.com/lwbqqyumidi/p/3769113.html Android官方文档和其他不少资料都对Activity生命周期进行了详细介绍,在结合资料和项目开发过程中遇到的问题,本文将对Activity生命周期进行一次总结. Activity是由Activity栈进管理,当来到一个新的Activity后,此Activity将被加入到Activity栈顶,之前的Activity位于此Activ

Android Activity生命周期的几个问题

每一个Android开发者都应该知道,android系统有四个重要的基本组件,即Activity(活动).Service(服务).Broadcast Receive(广播接收器)和Content Provider(内容提供器),其中,Activity是最重要的组件,打开你手机上的APP,你眼睛所能看到的都是Activity,下面将会介绍关于Activity生命周期的几个问题. 1 Activity生命周期的8个回调函数 下图是Activity的生命周期图,相信许多人都看过不止一次,但有的人是看到

Activity生命周期.lanchMode.保存状态

Activity生命周期 每一个Android应用程序在运行时,对于底层的Linux Kernel而言都是一个单独的进程,但是对于Android系统而言,因为局限于手机画面的大小与使用的考虑,不能把每一个运行中的应用程序窗口都显示出来. 所以通常手机系统的界面一次仅显示一个应用程序窗口,Android使用了Activity的概念来表示界面. 运行中的应用程序分为五大类,分别是: 前景模式:foreground process 可见模式:visible process 背景模式:backgroun

android --Activity生命周期具体解释

一. 再探Activity生命周期 为了研究activity的生命周期,简单測试代码例如以下. package com.example.testactivity; import android.app.Activity; import android.os.Bundle; import android.util.Log; import android.view.Menu; public class MainActivity extends Activity { private static fi

android --Activity生命周期详解

一. 再探Activity生命周期 为了研究activity的生命周期,简单测试代码如下. package com.example.testactivity; import android.app.Activity; import android.os.Bundle; import android.util.Log; import android.view.Menu; public class MainActivity extends Activity { private static fina

Android 面试之横竖屏切换的Activity生命周期

public class EngineerJspActivity extends Activity { private static String Tag = "EngineerJspActivity"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Log.d(Tag, "onCreate()"); setCont

Android 四大组件之Activity生命周期

写这篇博文之前,已经对android有一定的了解和认识.这篇博文主要讲述android的Activity的生命周期,这是android开发者必须掌握的知识.android的Activity组件拥有7个生命周期:onCreate().onStart().onResume().onPause().onStop().onDestory().onReStart(). 这7个生命周期分别在4个特定阶段进行调用. 开始Activity:当Activity开始运行的时候依次执行3个生命周期:onCreate.