`

Activity使用介绍

阅读更多

    Activity是用户正在访问的对象。几乎所有activities都与用户交互,所以Activity类为你生成一个你用setContentView(View) 放置你UI的窗口,而activities经常与满屏呈现在用户面前。它们也可以与另一种方式被使用:作为浮动窗口或者嵌入在另一个activity内(使用ActivityGroup)。几乎所有的子类都会实现的两个方法:

    onCreate(Bundle)是初始化你activity的地方。最重要的是,在这里你将调用setContentView(int)和布局资源来定义你的UI,然后使用findViewById(int)去检索需要与程序交互的widgets。

    onPause()是你处理用户离开你activity的地方。最重要的是,用户做的任何变动都应该在这里被committed(通常是用ContentProvider保存数据)

 

    为了使用Context.startActivity(),所有的activity类在程序包的AndroidManifest.xml必须有一个与当前activity一致的声明。

 

    在整个程序的生命周期,Activity类是很重要的部分,activities的启动是平台程序模型的基本部分。Android程序和生命周期的结构详细视图,请阅读开发者指南文档的Application Fundamentals。

 

    话题列表包括:

  1. Activity生命周期
  2. 配置改动
  3. 开启activities和获取结果
  4. 保存永久状态
  5. 权限
  6. 进程生命周期

    Activity生命周期

    activity在系统里是以activity栈堆被管理的。当一个activity被启动,它被放置到栈的最顶部而成为正在运行的activity--上一个activity总是被保留在栈堆里当前activity下面,将不会显示在前台,直到当前activity退出。

 

    activity本质上有4种状态:

  • 如果activity在屏幕的前台(位于栈堆顶部),它是活跃的或者正在运行中。
  • 如果activity失去了焦点但是仍然有效,(那是,一个新的没有满屏的或者透明的在你的activity顶部获取了焦点)它处于暂停状态,暂停状态的activity还是活着的(它维持着所有状态和成员的信息保持着attached to 窗口管理者),但是系统可以杀死这个进程,当系统处于极度内存不足的状态下。
  • 如果activity完全被另一个activity遮住,它就处于停止状态,它仍然会记住所有的状态和会员信息,但是不在显示给用户,所以它的窗口被隐藏,所以当系统需要内存的时候,该进程也经常被杀死。
  • 如果activity被中止或者停止,系统可以从内存由其他的要求它去结束而中止activity,或者简单的杀死它的进程。当它在被展示给用户,必须完全重新启动和重新储存到它之前的状态。

    接下来的图表展示了Activity主要的状态路径。方形块表示你能实现的执行操作回调方法当Activity在两种状态移动。椭圆形色块是Activity的几种主要状态。

 

    在你的activity内,有三个关键的循环你或许会感兴趣监视:

  • The  entire lifetime   of an activity happens between the first call to  onCreate(Bundle)   through to a single final call to  onDestroy() . An activity will do all setup of "global" state in onCreate(), and release all remaining resources in onDestroy(). For example, if it has a thread running in the background to download data from the network, it may create that thread in onCreate() and then stop the thread in onDestroy().
  • The  visible lifetime   of an activity happens between a call to  onStart()   until a corresponding call to  onStop() . During this time the user can see the activity on-screen, though it may not be in the foreground and interacting with the user. Between these two methods you can maintain resources that are needed to show the activity to the user. For example, you can register aBroadcastReceiver   in onStart() to monitor for changes that impact your UI, and unregister it in onStop() when the user an no longer see what you are displaying. The onStart() and onStop() methods can be called multiple times, as the activity becomes visible and hidden to the user.
  • activity的整个周期发生从首先调用  onCreate(Bundle) 到(待续.....)

 

 

  • 大小: 64.6 KB
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics