4、Android Activity的生命周期 Activity的生命周期
watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQveXV4aWt1b18x/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast" alt="">
1、完整生命周期
上图是Android Activity的生命周期图。当中Resumed、Paused、Stopped状态是静态的。这三个状态下的Activity存在时间较长。
(1)Resumed:在此状态时,用户能够与Activity进行交互,Activity在最前端
(2)Paused:在此状态时,Activity被另外一个Activity遮盖。此Activity不可接受用户输入信息。另外一个Activity来到最前面,半透明的,但并不会覆盖整个屏幕。
(3)Stopped:在此状态时,Activity全然被隐藏,不可见。
保留当前信息,Activity不运行不论什么代码。
(4)Created与Started:系统调用onCreate()后迅速调用onStart(),然后迅速运行onResume()。
以上就是Android的Activity整个生命周期。
2、主Activity
用户能够指定程序启动的主界面,此时被声明为“launcher或main”Activity的onCreate()方法被调用,成为程序的入口函数。
该入口Activity能够在AndroidManifest.xml中定义主Activity。此时,主Activity必须使用下面标签声明:
<activity android:name=".MainActivity" android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
3、一个新的Activity实例
系统首先调用新Activity的onCreate()方法,所以,我们必须实现onCreate()方法。如:声明UI元素、定义成员变量、配置UI等。
可是事情不宜太多,避免启动程序太久而看不到界面。
TextView mTextView; // Member variable for text view in the layout @Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); // Set the user interface layout for this Activity
// The layout file is defined in the project res/layout/main_activity.xml
file
setContentView(R.layout.main_activity); // Initialize member TextView so we can manipulate it later
mTextView = (TextView) findViewById(R.id.text_message); // Make sure we're running on Honeycomb or higher to use ActionBar APIs
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
// For the main activity, make sure the app icon in the action bar
// does not behave as a button
ActionBar actionBar = getActionBar();
actionBar.setHomeButtonEnabled(false);
}
}
onCreate()运行完即调用onStart()和onResume()方法。Activity不会在Created或者Started状态停留。
4、销毁Activity
Activity的最后一个回调是onDestroy(),系统会运行这种方法做为你的Activity要从系统中全然删除的信号。大多数APP不需实现此方法。由于局部类的references会随着Activity的销毁而销毁。而且Activity应该在onPause()和onStop()方法中运行清楚Activity资源的操作。
假设Activity在onCreate()时创建的后台线程。或者是其它有可能导致内存泄露的资源,你应该在onDestroy()时杀死它们。
@Override
public void onDestroy() {
super.onDestroy(); // Always call the superclass // Stop method tracing that the activity started during onCreate()
android.os.Debug.stopMethodTracing();
}
系统一般是在运行了onPause()与onStop()后在调用onDestroy()。除非在onCreate()中调用了finish()。比如,假设你的Activity仅仅是做了一个暂时的逻辑跳转功能,它使用用来决定跳转到下一个Activity。这样,你须要在onCreate()中调用finish()方法。系统就会直接调用onDestroy方法,其它生命周期就不会被运行。
5、暂停与恢复
@Override
public void 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()来保存用户改变的数据到永久存储上,当你确认用户期待那些改变可以自己主动保存的时候,才可以把那些数据存储到永久存储。
然而,应该避免在onPause()时运行CPU-intensive的工作。比如写数据到DB,由于他会导致切换Activity变得缓慢。这些工作应该放到onStop()中去坐。
此时Activity处于最前台。包含第一次创建时,此时,应该在onResume中初始化那些你在onPause方法里释放掉的组件。并运行那些Activity每次进入Resumed state都须要的初始化动作。
@Override
public void 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
虽然onPause方法在onStop之前调用,应应该使用onStop来运行CPU-intensive的shut-down操作。
如写数据到DB。
static final String STATE_SCORE = "playerScore";
static final String STATE_LEVEL = "playerLevel";
... @Override
public void onSaveInstanceState(Bundle savedInstanceState) {
// Save the user's current game state
savedInstanceState.putInt(STATE_SCORE, mCurrentScore);
savedInstanceState.putInt(STATE_LEVEL, mCurrentLevel); // Always call the superclass so it can save the view hierarchy state
super.onSaveInstanceState(savedInstanceState);
}
由于onCreate()方法会在第一次创建新的Activity实例与又一次创建之前被Destroy的实例时都被调用,你必须尝试读取Bundle对象之前检查它是否为NULL,假设为NULL。系统第一次创建新Activity。
否则是恢复被Destroy的Activity。
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); // Always call the superclass first // Check whether we're recreating a previously destroyed instance
if (savedInstanceState != null) {
// Restore value of members from saved state
mCurrentScore = savedInstanceState.getInt(STATE_SCORE);
mCurrentLevel = savedInstanceState.getInt(STATE_LEVEL);
} else {
// Probably initialize members with default values for a new instance
}
...
}
我们能够选择实现onRestoreInstanceState(),而不是在onCreate方法里恢复数据。onRestoreInstanceState()方法会在onStart()方法之后运行,系统只会在存在须要恢复的状态信息时才会调用onRestoreInstanceState()。因此不需检查Bundle是否为NULL。
public void onRestoreInstanceState(Bundle savedInstanceState) {
// Always call the superclass so it can restore the view hierarchy
super.onRestoreInstanceState(savedInstanceState); // Restore state members from saved instance
mCurrentScore = savedInstanceState.getInt(STATE_SCORE);
mCurrentLevel = savedInstanceState.getInt(STATE_LEVEL);
}
4、Android Activity的生命周期 Activity的生命周期的更多相关文章
- Android总结篇系列:Activity生命周期
Android官方文档和其他不少资料都对Activity生命周期进行了详细介绍,在结合资料和项目开发过程中遇到的问题,本文将对Activity生命周期进行一次总结. Activity是由Activit ...
- Android 中Activity生命周期分析:Android中横竖屏切换时的生命周期过程
最近在面试Android,今天出了一个这样的题目,即如题: 我当时以为生命周期是这样的: onCreate --> onStart -- ---> onResume ---> onP ...
- Android开发艺术1之Activity的生命周期
作为<Android开发艺术探索>这本书的第一篇博客,我就多说几句.本系列博客旨在对书中相关内容进行解读,简化,提供一个入门到提高的流程.不敢说书评,也不能说教程,只希望对有些人有帮助就好 ...
- 【转】Android总结篇系列:Activity生命周期
[转]Android总结篇系列:Activity生命周期 Android官方文档和其他不少资料都对Activity生命周期进行了详细介绍,在结合资料和项目开发过程中遇到的问题,本文将对Activity ...
- android.os.Process.killProcess(android.os.Process.myPid())与Activity生命周期的影响
如果通过finish方法结束了一个Activity,那么根据Activity的生命周期,则会自动调用Activity的销毁方法onDestory(),但是在项目中遇到这样的一个问题,就是Activi ...
- Android基础相关面试问题-activity面试问题(生命周期,任务栈,启动模式,跳转协议,启动流程)
关于Android的一些面试题在15年就已经开了这个专栏了,但是一直木有坚持收集,而每次面对想要跳槽时大脑一片空白,也有些恐惧,因为毕境面试都是纯技术的沟通,要想让公司对你的技术能有所认可会全方位的进 ...
- Android SDK上手指南:Activity与生命周期
Android SDK上手指南:Activity与生命周期 2013-12-26 15:26 核子可乐译 51CTO 字号:T | T Activity生命周期并不仅仅在用户运行应用程序之后才开始生效 ...
- android 入门-生命周期 activity
生命周期 activity http://blog.csdn.net/android_tutor/article/details/5772285 http://www.cnblogs.com/John ...
- Activity生命周期,切换,参数传递,bundle(包),值对象,Activity参数返回,Activity的启动模式
Activity代表手机屏幕的一屏,或是平板电脑中的一个窗口.它是android应用中最重要的组成单元之一,提供了和用户交互的可视化界面.在一个Activity中,可以添加很多组件,这些组件负责具体的 ...
随机推荐
- 无法将类型为“Microsoft.Office.Interop.Excel.ApplicationClass”的COM 对象强制转换为接口类型“Microsoft.Office.Interop.Excel._Application”
报错内容如下: 无法将类型为“Microsoft.Office.Interop.Excel.ApplicationClass”的COM对象强制转换为接口类型“Microsoft.Office.Inte ...
- Win8开机直接进桌面方法
最新的Win8系统由于新增开始屏幕(UI)界面,专门为触摸设备准备,并且很多喜欢尝鲜的电脑爱好者朋友在我们传统的电脑上安装了Win8系统,不少PC用户开始都不喜欢Win8开机后进入UI界面而非传统的电 ...
- .Net C#上传文件最大设置
<!--网页允许的最大设置节点--> <system.web> <httpRuntime targetFramework="4.5" maxReque ...
- 为什么说CLR是类型安全的
CLR总是知道托管堆上的对象是什么类型,这是CLR类型安全的前提.托管堆上的每个对象都有一个"类型对象指针",指向托管堆上Type对象的一个实例.我们总是可以通过System.Ob ...
- C#把文字转换成声音
在System.Speech命名空间下,SpeechSynthesizer类可以把文字读出来,一起来玩下~~ 首先在Windows窗体项目中引入System.Speech.界面部分: 后台代码也很简单 ...
- c#中何时使用Empty()和DefalutIfEmpty()
在项目中,当我们想获取IEnumerable<T>集合的时候,这个集合有可能是null.但通常的做法是返回一个空的集合. 假设有这样一个场景:当商店不营业时,返回一个空的IEnumerab ...
- C\C++各路高手以及操作系统专家请进来杀死这个进程
通常情况下编写一个程序,能够点击关闭button正常结束程序,也能够使用任务管理器结束任务,还能够使用taskkill等命令杀死进程,实在都不行也能够直接重新启动计算机. 可是,这些方法真的都管用吗? ...
- 一个自带简易数据集的模拟线性分类器matlab代码——实验训练
%%%% Tutorial on the basic structure of using a planar decision boundary %%%% to divide a collecti ...
- strstr实现
// strstr.c查找完全匹配的子字符串 #include<stdio.h> #include<string.h> char *my_strstr(const char * ...
- libjson 编译和使用 - 2. 配置使用lib文件
以下转自:http://blog.csdn.net/laogong5i0/article/details/8223448 1. 在之前的libjson所在的解决方案里新建一个控制台应用程序,叫Test ...