[Andriod官方训练教程]管理Activity的生命活动之停止和重启一个Activity

原文地址:https://developer.android.com/training/basics/activity-lifecycle/stopping.html

-------------------------------------------------------------------------------------------------------


Properly stopping and restarting your activity is an important process in the activity lifecycle that ensures your users perceive that your app is always alive and doesn't lose their progress. There are a few of key scenarios in which your activity is stopped and restarted:

  • The user opens the Recent Apps window and switches from your app to another app. The activity in your app that's currently in the foreground is stopped. If the user returns to your app from the Home screen launcher icon or the Recent Apps window, the activity restarts.
  • The user performs an action in your app that starts a new activity. The current activity is stopped when the second activity is created. If the user then presses theBack button, the first activity is restarted.
  • The user receives a phone call while using your app on his or her phone.

在activity的生命周期里,合适地停止和重启你的activity是一个非常重要的过程,这确保你的用户可以感到你的app总是活跃的而不是丢失了他们的进程。在以下几种情况下你的activity需要被停止或是重启:

  • 用户打开了“最近使用的应用程序”窗口,然后从你的app切换到另一个app。那么你的app里正在前台运行的activity就停止了。如果用户从主菜单里的开启图标或者“最近使用的应用程序”窗口返回到你的app,那activity就会重启。
  • 用户在你的app里执行了一个开始新的activity的动作。那么当前的activity在第二个activity创建时就停止了。如果用户后来就按下了返回按钮,那么第一个activity就会重启。
  • 用户在使用你的app时接到了一个电话。

The Activity class provides two lifecycle methods,onStop() andonRestart(), which allow you to specifically handle how your activity handles being stopped and restarted. Unlike the paused state, which identifies a partial UI obstruction, the stopped state guarantees that the UI is no longer visible and the user's focus is in a separate activity (or an entirely separate app).

Activity类提供了两个生命周期方法,onStop() 和onRestart(),它们允许你明确地控制你的activity该如何停止和重启。和暂停状态(只是局部的UI被阻塞)不同,停止状态确保UI对用户不再可见,而且用户的焦点在单独的一个activity上(或是完全是另一个单独的app)。

Note: Because the system retains your Activity instance in system memory when it is stopped, it's possible that you don't need to implement the onStop() andonRestart() (or evenonStart() methods at all. For most activities that are relatively simple, the activity will stop and restart just fine and you might only need to useonPause() to pause ongoing actions and disconnect from system resources.

注意:因为当你的Activity实例停止时系统在内存中仍然保留了它,你可能不需要实现onStop() 和onRestart()(甚至是onStart()方法。对于大多数相对简单的activity,它们可以好好地停止和重启,而你可能只需要使用onPause()来暂停正在进行中的动作并且和系统资源分离)。

Figure 1. When the user leaves your activity, the system callsonStop() to stop the activity (1). If the user returns while the activity is stopped, the system callsonRestart() (2), quickly followed byonStart() (3) andonResume() (4). Notice that no matter what scenario causes the activity to stop, the system always callsonPause() before callingonStop().

图1. 当用户离开你的activity时,系统调用onStop()来停止activity (1)。如果当activity停止时用户再次返回,系统调用onRestart() (2),紧接着调用onStart() (3)和onResume() (4)。你应该注意到无论哪种情况下使得activity停止,系统都将先调用onPause()再调用onStop()。

 

Stop Your Activity —— 停止你的活动

When your activity receives a call to the onStop() method, it's no longer visible and should release almost all resources that aren't needed while the user is not using it. Once your activity is stopped, the system might destroy the instance if it needs to recover system memory. In extreme cases, the system might simply kill your app process without calling the activity's finalonDestroy()callback, so it's important you useonStop() to release resources that might leak memory.

当你的activity收到一个onStop()方法的调用时,它将不再可见并且应该释放几乎所有用户在不使用它的所不需要的资源。一旦你的activity停止,如果系统需要回收系统内存,它就可能会销毁这个实例。在极端情况下,系统可能会杀死你的app进程而不需要调用activity的终极onDestroy()回调函数,因为使用onStop()来释放那些可能造成内存泄露的资源是很重要的。

Although the onPause() method is called beforeonStop(), you should useonStop() to perform larger, more CPU intensive shut-down operations, such as writing information to a database.

尽管onPause()方法在onStop()之前被调用,你应该使用onStop()来进行更大量的、更密集的CPU操作,例如向数据库写入信息。

For example, here's an implementation of onStop() that saves the contents of a draft note to persistent storage:

例如,下面onStop()的实现中永久保存了一个草稿记录的内容:

[java]  view plain copy print ?
  1. <span style="color:#000000;">@Override  
  2. protected void onStop() {  
  3.     super.onStop();  // Always call the superclass method first  
  4.   
  5.     // Save the note's current draft, because the activity is stopping  
  6.     // and we want to be sure the current note progress isn't lost.  
  7.     ContentValues values = new ContentValues();  
  8.     values.put(NotePad.Notes.COLUMN_NAME_NOTE, getCurrentNoteText());  
  9.     values.put(NotePad.Notes.COLUMN_NAME_TITLE, getCurrentNoteTitle());  
  10.   
  11.     getContentResolver().update(  
  12.             mUri,    // The URI for the note to update.  
  13.             values,  // The map of column names and new values to apply to them.  
  14.             null,    // No SELECT criteria are used.  
  15.             null     // No WHERE columns are used.  
  16.             );  
  17. }</span>  

 

When your activity is stopped, the Activity object is kept resident in memory and is recalled when the activity resumes. You don’t need to re-initialize components that were created during any of the callback methods leading up to the Resumed state. The system also keeps track of the current state for eachView in the layout, so if the user entered text into anEditText widget, that content is retained so you don't need to save and restore it.

当你的activity停止时,Activity对象被保留在内存中,然后在activity重新开始时被再次调用。你不需要再次初始化那些在任何回调函数中创建的部件。系统还将跟踪布局中每个View的当前状态,因此如果用户在EditText窗口中输入文字,那这些内容会被保留因此你不需要保存和重新载入它们。

Note: Even if the system destroys your activity while it's stopped, it still retains the state of theView objects (such as text in anEditText) in aBundle (a blob of key-value pairs) and restores them if the user navigates back to the same instance of the activity (thenext lesson talks more about using a Bundle to save other state data in case your activity is destroyed and recreated).

注意:即使在你的activity停止时系统销毁了它,系统仍然在一个Bundle(一个键-值对的二进制大对象)中保留了View对象的状态(例如一个EditText中的文本),如果用户导航到同样的activity实例系统将重新载入它们(next lesson中将探讨更多的关于当你的activity销毁和重建时如何使用一个Bundle来保存其他状态)。

 

Start/Restart Your Activity —— 启动/重启你的活动

When your activity comes back to the foreground from the stopped state, it receives a call toonRestart(). The system also calls theonStart() method, which happens every time your activity becomes visible (whether being restarted or created for the first time). TheonRestart() method, however, is called only when the activity resumes from the stopped state, so you can use it to perform special restoration work that might be necessary only if the activity was previously stopped, but not destroyed.

当你的activity从停止状态返回到前台时,它收到一个onRestart()的调用。系统还会调用onStart()方法,这个方法在你的activity变得可见时都会发生(不管是被重启还是第一次被创建)。但是,onRestart()方法仅在activity从停止状态重新开始时才会被调用,因此你需要使用它来执行特殊的恢复工作(仅在activity之前停止了但未被销毁的情况下的必要的工作)。

It's uncommon that an app needs to use onRestart() to restore the activity's state, so there aren't any guidelines for this method that apply to the general population of apps. However, because your onStop() method should essentially clean up all your activity's resources, you'll need to re-instantiate them when the activity restarts. Yet, you also need to instantiate them when your activity is created for the first time (when there's no existing instance of the activity). For this reason, you should usually use theonStart()callback method as the counterpart to theonStop() method, because the system callsonStart() both when it creates your activity and when it restarts the activity from the stopped state.

一个app需要使用onRestart()来重新载入activity的状态是不常见的,因此对于这个应用于母体app的方法没有任何指导。但是,因为你的onStop()方法本质上应该清除你的activity的所有资源,在activity重启时你将需要重新实例化它们。然而,在你的activity第一次创建(这时没有任何存在的activity实例)时,你还需要实例化它们。出于这个原因,你通常应该使用onStart()回调函数作为onStop()方法的对应版本,因为系统在创建你的activity和停止时重启activity都会调用onStart()

For example, because the user might have been away from your app for a long time before coming back it, theonStart() method is a good place to verify that required system features are enabled:

例如,因为用户在返回时可能已经离开你的app很长一段时间了,onStart()方法是一个核实系统性能是可用的的一个绝佳的地方:

[java]  view plain copy print ?
  1. @Override  
  2. protected void onStart() {  
  3.     super.onStart();  // Always call the superclass method first  
  4.       
  5.     // The activity is either being restarted or started for the first time  
  6.     // so this is where we should make sure that GPS is enabled  
  7.     LocationManager locationManager =   
  8.             (LocationManager) getSystemService(Context.LOCATION_SERVICE);  
  9.     boolean gpsEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);  
  10.       
  11.     if (!gpsEnabled) {  
  12.         // Create a dialog here that requests the user to enable GPS, and use an intent  
  13.         // with the android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS action  
  14.         // to take the user to the Settings screen to enable GPS when they click "OK"  
  15.     }  
  16. }  
  17.   
  18. @Override  
  19. protected void onRestart() {  
  20.     super.onRestart();  // Always call the superclass method first  
  21.       
  22.     // Activity being restarted from stopped state      
  23. }  

When the system destroys your activity, it calls the onDestroy() method for yourActivity. Because you should generally have released most of your resources withonStop(), by the time you receive a call toonDestroy(), there's not much that most apps need to do. This method is your last chance to clean out resources that could lead to a memory leak, so you should be sure that additional threads are destroyed and other long-running actions like method tracing are also stopped.

当系统销毁你的activity时,它将为你的Activity调用onDestroy()方法。因为你通常应该在onStop()里释放几乎所有的资源,等到你收到一个onDestroy()的调用时,大多数app不需要做太多的事情。这个方法是你清除那些会造成内存泄露的资源的最后的机会,因此你应该确保附加的线程被全部销毁,其他长期运行的动作,像追踪函数等,也同样被停止了。

你可能感兴趣的:(android,Activity,Activity生命周期,生命周期方法,重启activity)