Activity生命周期之stop和restart Activity

来源:互联网 发布:豪迪群发软件 编辑:程序博客网 时间:2024/05/16 18:10

以下是一些Activity 停止和重新启动的情况:

  • 突然接到电话
  • 当用户从一个A Activity启动另一个B Activity时候,A处于Stopped,当按返回键时,B被restart
  • 用户打开最近应用窗口,从你的app切换到别的app的时候。Activity处于Stopped,等到再切换回来时,Activity被restart
    注意:因为系统会将你的Activity缓存在内存中,所以有可能,你不用继承onRestart()(甚至是onStart()),特别简单的应用,可以只用onPause()来释放资源。
  • 当用户离开Activity时系统会调用onStop(),当用户再回来时,系统调用onRestart() 然后快速调用onStart()和onResume()。无论什么情况导致Activity 被stopped,都会先调用onPause(),然后调用onStop()

stop你的Activity

当你的Activity接受到onStop(),就会变为不可见。这时候需要释放几乎所有的资源。当Activity处于stopped状态,系统可能会因为回收系统内存资源而销毁Activity缓存的实例。极端的情况,系统可能会不回调onDestroy()而直接杀死你的程序进程。所以在onStop()中释放可能导致内存泄露的资源非常重要
尽管onPause()是在onDestroy()之前。你应该用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.             ); } 

注意:即使系统会销毁你的处于stopped状态的Activity,但是它人然会储存视图对象的状态(如:EditText中的文本)在bundle中,当用户回到同一个Activity实例时系统会恢复这些数据。(下篇文章会介绍如何使用bundle来存储状态信息)

restart并且start你的Activity

当你的Activity从Stopped状态恢复Resumed状态,会回调onRestart()。然后调用onStart()。每次Activity回到可见状态都需要调用onStart()函数。只有从stopped状态回到visible状态才会调用onRestart()。
用户可能离开你的app很久后才返回来。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     } 

一般不用onRestart()函数来恢复Actitiy的状态。

0 0
原创粉丝点击