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

简介:

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,应判断一下系统的的版本再决定是否执行。

1
2
3
4
5
6
7
// 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方法中。由下图也可以领会这个意思:

wKioL1ZQlH6BUzbeAAA-mVJomWI765.png

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.

  在代码里保存信息

1
2
3
4
5
6
7
8
9
10
11
12
13
14
@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
     }
     ...
}

 取出信息

1
2
3
4
5
6
7
8
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);
}






      本文转自屠夫章哥  51CTO博客,原文链接:http://blog.51cto.com/4259297/1715641 ,如需转载请自行联系原作者





相关文章
idea快速生成get set 构造方法的快捷键
idea快速生成get set 构造方法的快捷键
688 0
|
存储 消息中间件 监控
消息队列和应用工具产品体系-ARMS 服务的产品功能
消息队列和应用工具产品体系-ARMS 服务的产品功能
|
Java UED Python
【10月更文挑战第4天】「Mac上学Python 4」入门篇4 - PyCharm高效开发环境配置与使用技巧
本篇将详细介绍如何高效地使用PyCharm进行Python开发,内容涵盖PyCharm的主题设置、字体调整、常用快捷键、虚拟环境的管理、库安装与调试技巧等。通过本篇的学习,用户将能够充分利用PyCharm的功能,提升Python开发效率。
478 2
【10月更文挑战第4天】「Mac上学Python 4」入门篇4 - PyCharm高效开发环境配置与使用技巧
|
11月前
|
弹性计算 自然语言处理 Ubuntu
OS Copilot-操作系统智能助手-Linux新手小白的福音
OS Copilot是由阿里云推出的操作系统智能助手,专为Linux新手设计,支持自然语言问答、辅助命令执行等功能,极大提升了Linux系统的使用效率。用户只需通过简单的命令或自然语言描述问题,OS Copilot即可快速提供解决方案并执行相应操作。例如,查询磁盘使用量等常见任务变得轻松快捷。此外,它还支持从文件读取复杂任务定义,进一步简化了操作流程。虽然在某些模式下可能存在小问题,但总体上大大节省了学习和操作时间,提高了工作效率。
390 2
OS Copilot-操作系统智能助手-Linux新手小白的福音
|
数据采集 机器学习/深度学习 存储
使用 Python 清洗日志数据
使用 Python 清洗日志数据
264 2
ThreeJs绘制圆柱体
这篇文章介绍了在Three.js中绘制圆柱体的方法,包括创建圆柱体几何体、设置材质以及将其正确放置在三维场景中的技巧。
374 0
ThreeJs绘制圆柱体
|
机器学习/深度学习 资源调度 自然语言处理
循环神经网络RNN完全解析:从基础理论到PyTorch实战1
循环神经网络RNN完全解析:从基础理论到PyTorch实战
2281 0
PGA memory operation
PGA memory operation
306 1
|
存储 Java API
一篇文章讲明白luauserdata
一篇文章讲明白luauserdata
506 0
|
机器学习/深度学习 算法 关系型数据库
【PyTorch深度强化学习】DDPG算法的讲解及实战(超详细 附源码)
【PyTorch深度强化学习】DDPG算法的讲解及实战(超详细 附源码)
5475 1