码迷,mamicode.com
首页 > 其他好文 > 详细

GoogleDoc - 温故而知新Activity生命周期方法

时间:2015-11-22 23:38:46      阅读:573      评论:0      收藏:0      [点我收藏+]

标签:android思考

3.创建Activity一般人所不知道的地方

  1)Activity里的各个生命周期的方法一般执行什么代码   

  》》onCreate() method shows some code that performs some fundamental setup for the activity, such as declaring the user interface (defined in an XML layout file), defining member variables, and configuring some of the UI.(填充View,定义变量。。。)

   在onCreate()方法里,对于高版本的API,应判断一下系统的的版本再决定是否执行。

// 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);
    }

   Caution: Using the SDK_INT to prevent older system‘s from executing new APIs works in this way    on Android 2.0 (API level 5) and higher only. Older versions will encounter a runtime exception.

 

 》》onPause()一般与onStop一起执行,应该注意它的特殊情况。

 As long as the activity is still partially visible but currently not the activity in focus, it       remains paused.(Activity可见,但是没有获得焦点就会进行pause状态)

   As your activity enters the paused state, the system calls theonPause() method on your Activity, which allows you to stop ongoing actions that should not continue while paused (such as a video) or persist any information that should be permanently saved in case the user continues to leave your app. If the user returns to your activity from the paused state, the system resumes it and calls the onResume() method. (在onPause方法里可以停止一些操作,保留信息当用户离开app的时候,当走出paused状态时,Activity会执行onResume方法)

 

   You should usually use the onPause() callback to:


    • Stop animations or other ongoing actions that could consume CPU.(停止动画)

    • Commit unsaved changes, but only if users expect such changes to be permanently saved when they leave (such as a draft email).

    • Release system resources, such as broadcast receivers, handles to sensors (like GPS), or any resources that may affect battery life while your activity is paused and the user does not need them.(释放网络资源)

 

Generally, you should not use onPause() to store user changes (such as personal information entered into a form) to permanent storage. The only time you should persist user changes to permanent storage withinonPause() is when you‘re certain users expect the changes to be auto-saved (such as when drafting an email). However, you should avoid performing CPU-intensive work during onPause(), such as writing to a database, because it can slow the visible transition to the next activity (you should instead perform heavy-load shutdown operations during onStop()).

You should keep the amount of operations done in the onPause() method relatively simple in order to allow for a speedy transition to the user‘s next destination if your activity is actually being stopped.

上面的文字中着重强调了,如果想要快速的跳转到下一个Activity,不要将一些重量级的操作放在onPause里,而应该放在onStop方法中。由下图也可以领会这个意思:

技术分享

Note: When your activity is paused, the Activity instance 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.

一般初始化相机的方法写在onResume()方法中,release camera的逻辑写在onPause中。


 》》onStop() 一般用来释放资源,防止应用线程被杀死。(按下Home键)

   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 final onDestroy() callback, so it‘s important you use onStop() to release resources that might leak memory.

   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 each View in the layout, so if the user entered text into an EditText widget, that content is retained so you don‘t need to save and restore it.(Activity stop之前,对象仍然会保存在内存当中,没有必要重新初始化组件了)

 Note: Even if the system destroys your activity while it‘s stopped, it still retains the state of the View objects (such as text in an EditText) in a Bundle (a blob of key-value pairs) and restores them if the user navigates back to the same instance of the activity (the next lesson talks more about using a Bundle to save other state data in case your activity is destroyed and recreated).(当Activity stop的时候,即使Activity被销毁了,仍然可以保存View的状态,当用户开启新的Activity实例时会恢复它们) 

  》》onRestart() 当Activity从stop状态返回到前台时执行这个方法 

  When your activity comes back to the foreground from the stopped state, it receives a call to onRestart().The system also calls the onStart() method, which happens every time your activity becomes visible (whether being restarted or created for the first time) 

  Google重点强调了onRestart与onStart的区别,强烈要求onStart()与onStop配对使用,因为onRestart只有在从stop状态返回的时候被调用,在Activity创建的时候并不会被调用。

  theonStart() method is a good place to verify that required system features are enabled:(一般在onStart()方法里进行一些系统特殊是否可用的判断)

  2)保存Activity中View的信息

  Caution: Your activity will be destroyed and recreated each time the user rotates the screen. When the screen changes orientation, the system destroys and recreates the foreground activity because the screen configuration has changed and your activity might need to load alternative resources (such as the layout).  (比如在切屏的时候,Activity会销毁,但Activity组件数据会消除怎么办?)

  Note: In order for the Android system to restore the state of the views in your activity, each view must have a unique ID, supplied by the android:id attribute.(保存View的信息,要求View必须有一唯一的ID值)

  

  具体怎么保存View的状态,View的状态又会传到哪儿去?

To save additional data about the activity state, you must override the onSaveInstanceState() callback method. The system calls this method when the user is leaving your activity and passes it the Bundle object that will be saved in the event that your activity is destroyed unexpectedly. If the system must recreate the activity instance later, it passes the same Bundle object to both the onRestoreInstanceState() and onCreate()methods.

  在代码里保存信息

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

 取出信息

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);
}


本文出自 “行意天下” 博客,请务必保留此出处http://4259297.blog.51cto.com/4249297/1715641

GoogleDoc - 温故而知新Activity生命周期方法

标签:android思考

原文地址:http://4259297.blog.51cto.com/4249297/1715641

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!