您的位置:首页 > 其它

管理Activity的生命周期

2012-11-14 23:45 295 查看
一、理解生命周期的回调函数



当用户要离开正在使用的Activity时,系统为了取消这个Activity就会调用别的方法来使得Activity从最前端的状态退下来。在某些情况下,activity只会移动部分沿着金字塔和等待(例如当用户选择另一个activity时),从那一点上activity可以返回到顶部(如果用户回到activity)恢复到之前用户所停止的地方。



Resumed
在这种状态下,activity是在前台而且用户可以和它进行互动(有时也称“运行”状态)

Paused
在这种状态下,activity被另一个activity遮掩一部分--另一个activity是在前台而且还是半透明或者没有覆盖整个屏幕。这个暂停的活动不能够接收用户的输入和操作任何代码。

Stopped
在这种状态下,activity对用户来说是完全隐藏不可见的;它考虑到是在后台。当停止之后,活动实例和它所以的状态信息例如成员变量是被保存的,但是却不能执行任何代码。
其他的状态下都是短暂的,系统迅速的从他们移动到下一个状态通过调用下一个生命周期回调方法。也就是,系统调用OnCreat()之后,会很快调用onStart(),紧接着的是
onResume()

二、指定你的应用程序的发射活动
当用户从主菜单当中选择你的应用程序的图标时,系统在你的应用程序中为活动调用onCreate()方法,你已经宣称“发射器”(或“主要”)这个活动的服务是作为主要入口点到你的应用程序的用户
界面。
你的应用程序的主活动必须先在manifest中通过<intent-filter>来定义,它包括MAIN动作和LAUNCHER类。例如:

<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>

1.1、创建一个新实例
例如,你实现onCreate()时应该定义用户界面和可能的实例化类范围变量。


下面的例子是关于onCreate()方法展示一些代码,为活动执行一些基础设置,例如宣布用户界面,定义成员变量和配置一些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()方法。


1.2、销毁activity

当Activity被从内存中移除时,一般发生在执行finish方法时或者Android调用
onPause()

onStop()
方法的时候

@Override
public void onDestroy() {
super.onDestroy();  // Always call the superclass

// Stop method tracing that the activity started during onCreate()
android.os.Debug.stopMethodTracing();
}


二、暂停和回复activity

当一个半透明的activity掩盖了你的activity时,系统就会调用
onPause()
,activity等待在暂停的状态。如果用户返回到activity当它一直出于暂停状态时,系统就会
onResume()




2.1暂停你的activity

OnPaused的回调函数:

a.停止动画或其他进行行动能消耗。

b.提交未保存的更改,但如果用户希望这种变化是永久保存在他们离开时(如撰写电子邮件)。

c.释放系统资源,如广播接收器,处理传感器(如全球定位系统),或任何资源,会影响电池寿命的同时你的活动被暂停,用户不需要他们。

2.2恢复你的activity

当用户从暂停状态下恢复你的应用程序时,系统会调用
onResume()
方法。

下面的例子onresume()是对应的onpause()上面的例子,所以它初始化相机的释放活动时暂停。

@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
}
}

三、停止和重新启动一个activity

有几个关键的场景中,你的activity会被停止并重新启动:

a.用户打开最近使用的应用程序窗口,从您的应用程序转换到另一个程序。这个activity在您的应用程序,现在在前台是停止的。如果用户从主屏幕启动图标返回到你的应用程序或最近的活动窗口,重新启动。

b.用户执行一个动作,在你的应用程序启动一个新的activity。

c.当第二个activity创建之后,现在的activity就会停止。如果用户按下返回按钮,则第一个activity就会重新启动。

d.当用户在他或她的电话上正在使用你的应用程序时收到来电。

activity类提供了两种生命周期的方法,onstop()和onrestart(),让你专门处理如何处理被停止并重新启动您的活动。



当用户离开你的activity时,系统调用
onStop()
来停止活动;当activity出于停止状态时如果用户返回,则系统调用
onRestart()
;然后迅速地通过
onStart()

onResume()
接下;注意,不管是什么情况导致停止活动,系统都会在调用
onStop()
之前调用
onPause()


3.1停止你的activity

当你接到一个电话而调用onstop()方法,它不再是可见的而且当用户不需要使用它时它应该释放几乎所有资源。一旦你的活动停止,系统可能会破坏实例,如果需要恢复系统内存。。

虽然onpause()方法在onstop()之前被调用,但是你应该使用onstop()执行更大,更多的处理器密集关机操作,比如往数据库里面写信息。

例如,这是一个实现onstop()方法来持久保存草案记录:

@Override
protected void 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 = new ContentValues();
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.
);
}


当它停止的时候即使系统摧毁了你的activity,但它仍然保持着视图对象在一个包和恢复他们的状态,如果用户返回到同一个实例活动。

3.2启动和重新启动你的activity

当你的activity从停止状态回到前台时,它接收一个onrestart()方法的调用。该系统也称为onstart()方法,其中每一次的发生都使你的activity活动变得可见。该onrestart()方法,然而,被称为只有当活动从停止状态恢复,所以你可以用它来执行特殊的可能是必要的恢复工作,如果activity只是以前停止的,而不是被破坏的。

例如,因为用户可能会离开你的应用程序,很久才回来,那onstart()方法是个不错的地方,用以验证系统所需的启用功能:

@Override
protected void onStart() {
super.onStart();  // Always call the superclass method first

// The activity is either being restarted or started for the first time
// so this is where we should make sure that GPS is enabled
LocationManager locationManager =
(LocationManager) getSystemService(Context.LOCATION_SERVICE);
boolean gpsEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);

if (!gpsEnabled) {
// Create a dialog here that requests the user to enable GPS, and use an intent
// with the android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS action
// to take the user to the Settings screen to enable GPS when they click "OK"
}
}

@Override
protected void onRestart() {
super.onRestart();  // Always call the superclass method first

// Activity being restarted from stopped state
}

四、重建一个activity

保存额外的活动状态数据,你必须重写onsaveinstancestate()回调方法。当用户离开你的活动和通过捆绑对象将被保存在事件您的活动破坏意外时系统调用该方法。如果系统必须重新创建活动实例后,则它通过同一包对象的onrestoreinstancestate()和oncreate()方法。



当系统开始停止你的activity时,它调用onsaveinstancestate()方法;

所以你可以指定你想要保存的额外的状态数据,在该活动实例必须重建的情况下;

如果activity被摧毁而且同一实例又必须重建时,系统状态数据会定义在oncreate()方法和onrestoreinstancestate()方法;
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: