『Android』activity的生命周期

来源:互联网 发布:中兴和华为知乎 编辑:程序博客网 时间:2024/06/06 09:09


  • Does not crash if the user receives a phone call or switches to another app while using your app.
  • Does not consume valuable system resources when the user is not actively using it.
  • Does not lose the user's progress if they leave your app and return to it at a later time.
  • Does not crash or lose the user's progress when the screen rotates between landscape and portrait orientation.
了解生命周期的作用:

1.在用户接电话或者切换到其他应用的时候不崩溃

2.在用户不激活应用的时候,释放系统资源

3.在用户从其他应用回到本应用时,可以记录用户的使用数据(进程)

4.当用户切换显示的时候(横向显示或者纵向显示)不丢失用户数据


Resumed
In this state, the activity is in the foreground and the user can interact with it. (Also sometimes referred to as the "running" state.)
Paused
In this state, the activity is partially obscured by another activity—the other activity that's in the foreground is semi-transparent or doesn't cover the entire screen. The paused activity does not receive user input and cannot execute any code.
Stopped
In this state, the activity is completely hidden and not visible to the user; it is considered to be in the background. While stopped, the activity instance and all its state information such as member variables is retained, but it cannot execute any code.

 The system calls onDestroy() after it has already called onPause() and onStop() in all situations except one: when you call finish() from within the onCreate() method. In some cases, such as when your activity operates as a temporary decision maker to launch another activity, you might call finish()from within onCreate() to destroy the activity. In this case, the system immediately calls onDestroy()without calling any of the other lifecycle methods.


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()).

原创粉丝点击