Activity生命周期

回调函数

onCreate() 创建

onStart() 运行

onResume() 获取焦点

onPause() 失去焦点

onStop() 暂停

onDestroy 销毁

onRestart()

onSaveInstanceState()

onRestoreInstanceState()

onWindowFocusChanged()

PS:

Log Level

Method

Describtion

ERROR

Log.e(…)

错误

WARNING

Log.w(…)

警告

INFO

Log.i(…)

信息型消息

DEBUG

Log.d(…)

调试输出:可能被过滤掉

VERBOSE

Log.v(…)

只用于开发

 

  所有的日志记录方法都有两种参数签名:String类型的tag参数和msg参数;除tag和msg参数外再加上Throwable实例参数。附加的Throwable实例参数为应用抛出异常时记录异常信息提供方便。

 

Resumed:在这个状态,activity在前台和用户能够和它交互。

Paused:在这个状态,activity部分被其他在前台半透明的activity挡住,暂停的activity无法接收用户输入也无法执行代码。

 

代码清单:

package com.example.administrator.activitylife;

import android.app.ActionBar;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.PersistableBundle;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends Activity {

    private static final String TAG="ActivityLife";
    private Context context=this;
    private int param=1;
    private int getParam=0;
    TextView txt;
    //Activity创建时被调用
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.i(TAG, "onCreate called");
        setContentView(R.layout.activity_main);
        Button btn= (Button) findViewById(R.id.btn);
        txt= (TextView) findViewById(R.id.txt);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent=new Intent(MainActivity.this,TargetActivity.class);
                startActivity(intent);
//                AlertDialog.Builder builder=new AlertDialog.Builder(MainActivity.this).setTitle("Alert");
//                builder.create().show();
            }
        });
//        if (Build.VERSION.SDK_INT>=Build.VERSION_CODES.HONEYCOMB){
//            ActionBar actionBar=getActionBar();
//            actionBar.setHomeButtonEnabled(false);
//        }
    }
    //Activity创建或者从后台重新回到前台时被调用
    @Override
    protected void onStart() {
        super.onStart();
        Log.i(TAG,"onStart called.");
    }
    //Activity从后台重新回到前台时被调用
    @Override
    protected void onRestart() {
        super.onRestart();
        Log.i(TAG, "onRestart called.");
    }
    //Activity创建或从被覆盖、后台重新回到前台时被调用
    @Override
    protected void onResume() {
        super.onResume();
        Log.i(TAG, "onResume called.");
    }
    //Activity被覆盖到下面(仍部分可见)、锁屏时被调用
    @Override
    protected void onPause() {
        super.onPause();
        Log.i(TAG,"onPause called.");
    }
    //退出当前Activity或者跳转到新Activity时被调用(完全不可见)
    @Override
    protected void onStop() {
        super.onStop();
        Log.i(TAG,"onStop called.");
    }
    //Activity被系统杀死时被调用
    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.i(TAG,"onDestroy called.");
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        outState.putInt("param",param);
        Log.i(TAG,"onSaveInstanceState called. param="+param);
        super.onSaveInstanceState(outState);
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        getParam=savedInstanceState.getInt("param")+1;
        txt.setText(Integer.toString(getParam));
        Log.i(TAG,"onRestoreInstanceState called. getParam="+getParam);
        super.onRestoreInstanceState(savedInstanceState);
    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        Log.i(TAG,"");
    }
}

 

 

 

(1)       activity第一次创建并启动的时候

PsonCreate()在整个生命周期中只会调用一次

 

 

 

 

(2)       当跳转到其他Activity,按下Home键回到主屏或锁屏(完全不可见):

    

 

onStop:

activity被调用onStop()方法时,应该释放那些用户没有用的资源。当activity处于stopped状态时,如果系统需要恢复系统内存时系统可能会销毁这个实例。最极端的情况下,系统可能会直接杀死你的APP进程而不是去调用onDestroy回调方法,所以使用onStop()来释放可能内存泄露的资源很重要。当activity处于stopped状态时,你不需要再初始化那些已经被创建组件因为它们都被保存在内存中。系统也会跟踪布局中每一个组件的当前状态,所以如果用户输入内容在EditText中,它的内容将已经被保存所以你不需要另外添加操作来保存和恢复它。

虽然onPause被调用在onStop前面,你应该使用onStop()来执行更大的,更多的CPU密集关闭操作比如写入信息到数据库中。

 

For example, here's an implementation of onStop() that saves the contents of a draft note to persistent storage:

               @Override
protectedvoid onStop(){
   
super.onStop();  // Always call the superclass method first

   
// Save the note's current draft, because the activity is stopping
   
// and we want to be sure the current note progress isn't lost.
   
ContentValues values =newContentValues();
    values
.put(NotePad.Notes.COLUMN_NAME_NOTE, getCurrentNoteText());
    values
.put(NotePad.Notes.COLUMN_NAME_TITLE, getCurrentNoteTitle());

    getContentResolver
().update(
            mUri
,    // The URI for the note to update.
            values
,  // The map of column names and new values to apply to them.
           
null,    // No SELECT criteria are used.
           
null     // No WHERE columns are used.
           
);
}

 

(3)       从后台回到前台或解锁屏幕

 

 

(4)       当弹出对话框风格的activity,也就是当前activity部分不可见时会被调用该方法

    

 

(该方法更多的时候activity被完全覆盖,并很快进入了stopped状态,因此应经常使用onPause()方法来:

A.停止动画或其他正在进行的可能消耗GPU的行为

B.提交尚未保存的修改内容,但仅仅在如果用户期望这些改变能够在他们离开该activity的时候永久的保存起来,例如一个email草稿。

C.释放系统资源,比如broadcast receiverhandler to sensors(传感器,比如GPS)或者任何可能影响电池使用寿命的资源当你的activity已经处于paused状态并且用户不需要它。

代码:

@Override
publicvoid onPause(){
   
super.onPause();  // Always call the superclass method first

   
// Release the Camera because we don't need it when paused
   
// and other activities might need to use it.
   
if(mCamera !=null){
        mCamera
.release();
        mCamera
=null;
   
}
}

通常,你不应该使用onPause()去将用户修改(例如输入在表单中的用户信息)储存到永久储存中。唯一一次你需要将用户修改保存到永久储存中的情况是当你确定用户期望修改能被自动保存(例如起草一份email时)。

然而,你应该避免在onPause()中执行密集型CPU工作,例如写入数据库,因为它会放慢到下一个activity的可见过渡(你应该代替执行重载关闭操作在onStop()中)。

为了有一个快速过渡到用户的下一个目的地如果你的activity实际上被停止时,你应该保持在onPause()方法中的作业量相对简单。

NoteWhen your activity is paused, the Activity instance is kept resident in memory and is recalled when the activity resumes. You don’t need to re-initialize components that were created during any of the callback methods leading up to the Resumed state.

注:以上内容来自http://developer.android.com/training/basics/activity-lifecycle/pausing.html

        

5)当activity又全部可见时该方法被调用(从系统内存中重新恢复的时候)

        

    When the user resumes your activity from the Paused state, the system calls the onResume() method.

Be aware that the system calls this method every time your activity comes into the foreground, including when it's created for the first time. As such, you should implement onResume() to initialize components that you release during onPause() and perform any other initializations that must occur each time the activity enters the Resumed state (such as begin animations and initialize components only used while the activity has user focus).

  这里我的理解是当用户从Paused状态恢复activity时调用onResume()方法。每一次被系统调用onResume()方法唤醒时,包括它第一次被创建时。你应该实现onResume这个方法来初始化那些在执行onPause()时被收回销毁的组件,例如动画和一些只用获得焦点才会使用到的组件。

The following example of onResume() is the counterpart to the onPause() example above, so it initializes the camera that's released when the activity pauses.

@Override
publicvoid onResume(){
   
super.onResume();  // Always call the superclass method first

   
// Get the Camera instance as the activity achieves full user focus
   
if(mCamera ==null){
        initializeCamera
();// Local method to handle camera init
   
}
}

6)当退出当前activity

        

 

1、  onWindowFocusChanged:activity窗口获得或失去焦点时被调用。

2、  onSaveInstanceState:onPause之后调用

(1)Activity被覆盖或退居后台之后,系统资源不足将其杀死;

(2)改变屏幕方向

(3)跳转到其他Activity、回到主屏,自身退居后台或锁屏(保存当前各个View的状态)

3、   onRestoreInstanceState:onStart后被调用(仅仅当有保存的状态需要恢复)

(1)Activity被覆盖或退居后台之后,系统资源不足将其杀死,用户又回到此activity;

(2)改变屏幕方向,重建activity

 

 

 

 

 

posted @ 2016-02-01 11:58  戎码之路  阅读(267)  评论(0编辑  收藏  举报