Android开发入门之Activity生命周期

Activity生命周期:


第一步:新建一个Android工程命名为LifeCycle目录结构如下图:


第二步:修改activity_main.xml布局文件代码如下:

<LinearLayout 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"
    android:orientation="vertical"
    tools:context=".MainActivity" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="startActivity"
        android:text="打开OtherActivity" />

</LinearLayout>

第三步:编写MainActivity类:

package cn.leigo.lifecycle;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;

public class MainActivity extends Activity {
	private static final String TAG = "MainActivity";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		Log.i(TAG, "onCreate(Bundle savedInstanceState)");
	}

	@Override
	protected void onStart() {
		super.onStart();
		Log.i(TAG, "onStart()");
	}

	@Override
	protected void onRestart() {
		super.onRestart();
		Log.i(TAG, "onRestart()");
	}

	@Override
	protected void onResume() {
		super.onResume();
		Log.i(TAG, "onResume()");
	}

	@Override
	protected void onPause() {
		super.onPause();
		Log.i(TAG, "onPause()");
	}

	@Override
	protected void onStop() {
		super.onStop();
		Log.i(TAG, "onStop()");
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		Log.i(TAG, "onDestroy()");
	}

	public void startActivity(View v) {
		Intent intent = new Intent(this, OtherActivity.class);
		startActivity(intent);
	}

}

第三步:编写OtherActivity类:

通过查看Log可以看到
显示到前台时:


1.按后退键时:

整个生命周期:

onCreate()->onStart()->onResume()->onPause()->onStop()->onDestroy()


2.打开另外一个Activity(完全覆盖MainActivity)时:

整个生命周期:

onCreate()->onStart()->onResume()->onPause()->onStop()->onRestart()->onStart()->onResume()->onPause()->onStop()->onDestroy()


2.打开另外一个Activity(未完全覆盖MainActivity)时:

在AndroidManifest.xml中为OtherActivity配置:

android:theme="@android:style/Theme.Dialog"


整个生命周期:

onCreate()->onStart()->onResume()->onPause()->onResume()->onPause()->onStop()->onDestroy()


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值