Activity生命周期管理之三——Stopping或者Restarting一个Activity

来源:互联网 发布:简便算法公式 编辑:程序博客网 时间:2024/05/19 12:41


适当stop和restart你的Activity对于确保用户的数据没有丢失是很重要的,下面是几个需要stop和restart一个Activity的情况:

  • 用户打开最近使用窗口并且切换到其他app,这个Activity被stop,如果用户点击app icon或者从最近使用里返回app,Activity restart
  • 从当前Activity打开另一个Activity,当前Activity在另一个Activity被创建时stop,当用户点返回键时,Activity restart
  • 用户接电话时

与paused状态不同,stopped的状态下Activity完全不可见,用户焦点完全在另一个Activity或另一个App的Activity

Note: 因为系统会在内存中保持Activity实例,所以一般app不用实现onStop或者onRestart方法,甚至onStart方法,因为大多app比较简单,可能只实现onPause方法处理一些资源或者数据即可

Stop你的Activity


当接收到onStop方法调用时,Activity不再可见,应该释放几乎所有不需要使用的资源,一旦Activity stop,如果系统需要回收系统能存,可能销毁实例,极端情况下,系统可能连onDestroy都不调用而直接杀掉进程,所以使用onStop方法处理会导致内存泄露的资源非常重要

即使onPause在onStop之前调用,也应该在onStop中处理更复杂,更耗CPU的操作,像写入数据库等

例如,下面例子像持久存储写入一个草稿

@Overrideprotected 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处在stopped状态时,Activity对象会保持在内存中,不需要重新初始化resumed状态之前初始化的组件,系统也会跟踪布局中View的状态,所以如果在EditText中有输入也不必保存

Note: 即使系统在stopped状态下destroy你的Activity,View的状态仍然被保存在一个Bundle中,当用户再次回到这个Activity事例时还会存在

Start/Restart你的Activity


当Activity从stopped状态到前台来,接到onRestart方法调用,系统也会调用onStart方法,因为每次Activity变得可见时系统都会调用onStart方法,无论创建还是restart,onRestart方法只是在stopped状态resume时才调用,所以可以在在其中执行一些特殊的恢复操作,例如用户长时间离开后,在onStart方法中确保系统状态是否可以是再好不过的了

@Overrideprotected 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"    }}@Overrideprotected void onRestart() {    super.onRestart();  // Always call the superclass method first        // Activity being restarted from stopped state    }


因为多数资源在onStop方法中释放,所以一般不用实现onDestroy方法,但也要确保所有可能导致内存泄露的资源已经被释放

 

原创粉丝点击