一步步学习android(3)

Activities


An Activity is an application component that provides a screen with which users can interact in order to do something, such as dial the phone, take a photo, send an email, or view a map. Each activity is given a window in which to draw its user interface. The window typically fills the screen, but may be smaller than the screen and float on top of other windows.


An application usually consists of multiple activities that are loosely bound to each other. Typically, one activity in an application is specified as the "main" activity, which is presented to the user when launching tha application for the first time. Each activity can then start another activity in order to perform different actions. Each time a new activity starts, it is pushed onto the back stack and takes user focus.


The back stack abides to the basic "last in, first out" stack mechanism, so, when the user is done with the current activity and presses the Back button, it is popped from the stack(and destroyed) and the previous activity resumes. (The back stack is discussed more in the Tasks and Back Stack document.)


When an activity is stopped because a new activity starts, it is notified of this change in state through the activity's lifecycle callback methods. There are several callback methods that an activity might receive, due to a change in its state--whether the system is creating it, stopping it, resuming it, or destroying it--and each callback provides you the opportunity to perform specific work that's appropriate to that state chage. For instance, when stopped, your activity should release any large objects, such as network or database connections. When the activity resumes, you can reacquire the necessary resources and resume actions that were interrupted. These state transactions are all part of the activity lifecycle.


The rest of this document discusses the basics of how to build and use an activity, including a complete discussion of how the activity lifecycle works, so you can properly manage the transition between various activity states.


Crating an activity


To create an activiy, you must create a subclass of Activity(or an existing subclass of it). In your subclass, you need to implement callback methods that the system calls when the activity transitions between various states of its lifecycle, such as when the activity is being created, stopped, resumed, or destroyed. The two most important callback methods are:


onCreate()

You must implement this method. The system calls this when creating your activity. Within your implementation, you should initialize the essential components of your activity. Most importantly, this is where you must call setContentView() to define the layout for the activity's user interface.


onPause()

The system calls this methods as the first indication that the user is leaving your activity(though it does not always mean the activity is being destroyed). This is usually where you should commit any changes that should be persisted beyond the current user session(because the user might not come back).


There are several other lifecycle callback methods that you should use in order to provide a fluid user experience between activities and handle unexpected interuptions that cause your activity to be stopped and even destoryed. All of the lifecycle callback methods are discussed later, in the section about Managing the Activity Lifecycle.



The <action> element specifies that this is the "main" entry point to the application. The <category> element specifies that this activity should be listed in the system's application launcher(to allow users to launch this activity).


If you intend for your application to be self-contained and not allow other appliations to active its activities, then you don't need any other intent filters. Only one activity should have the "main" action and "launcher" category, as in the previous example. Activities that you don't want to make avaliable to other appliations should have no intent filtersand you can start them yourself using explicit intents(as didcussed in the following section).


This is where intents are really valuable--you can create an intent that describes an action you want to perform and the system launches the appropriate activity from another application. If there are multiple activities that can handle the intent, then the user can select which one to use.


Starting an activity for a result

Sometimes, you might want to receive a result from the activity that you start. In that case, start the activity by calling startActivityForResult()(instead of startActivity()). To then receive the result from the subsequent activity, implement the onActivityResult() callback method. When the subsequent activity is done, it returns a result in an Intent to your onActivityResult() method.


Shutting Down an Activity

You can shut down an activity by calling its finish() method. You can also shut down a seperate activity that you previously started by calling finishActivity().

In most cases, you should not explicitly finish an activity using these methods. As discussed in the following section about the activity lifecycle, the Android system manages the life of an activity for you, so you do not need to finish your own activities. 


Lifecycle of Activity


Resumed

The activity is in the foreground of the screen and has user focus.(This state is also sometimes referred to as "running").

Paused

Another activity is in the foreground and has focus, but this one is still visible. That is, another activity is visible on top of this one and that activity is partially transparent or doesn't cover the entire screen. A paused activity  is completely alive(the Activity object retained in memory, it maintains all state and member information, and remains attached to the window manager), but can be killed by the system in extremely low memory situations.

Stopped

The activity is completely obscured by another activity(the activity is now in the "backgound"). A stopped activity is also still alive(the Activity object is retained in memory, it maintains all state and member information, but is not attached to the window manager). However, it is no longer visible to the user and it can be killed by the system when memory is needed elsewhere.


If an activity is paused or stopped, the system can drop it from memory either by asking it to finish(calling its method finish()), or simply killing its process. When the activity is opened again(after being finished or killed), it must be created all over.



Implementing the lifecycle callbacks

When an activity transitions into and out of the different states described above, it is notified through various callback methods. All of the callback methods are hooks that you can override to do appropriate work when the state of your activity changes.


Your implementation of these lifecycle methods must always call the superclass implementation before doing any work.



Saving activity state

The introduction of Managing the Activity Lifecycle briefly mentions that when an activity is paused or stopped, the state of the activity is retained. This is true because the Activity object is still held in memory when it is paused or stopped--all information about its members and current state is still alive. Thus, any changes the user made within the actiivty are retained so that when the activity returns to the foreground(when it "resumes"), those changes are still there.


The system calls onSaveInstanceState() before making the activity vulnearable to destruction. The system passes this method a Bundle in which you can save information about the activity as name-value paris, using methods such as putString() and putInt(). Then, if the system kills your application process and the user navigates back to your activity, the system recreates the activity and passes the Bundle to both onCreate() and onRestoreInstanceState(). Using either of these methods, you can extract your saved state from the Bundle and restore the activity state. If there is no state information to restore, then the Bundle passed to you is null(which is the case when the activity is created for the first time).


Although the default implementation of onSaveInstanceState() saves useful information about your activity's UI, you still might need to override it to save additional information. For example, you might need to save member values that changed during the activity's life(which might correlate to values restored in the UI, but the members that hold those UI values are not restored, by default).


Because the default implementation of onSaveInstanceState() helps save the state of the UI, if you override the method in order to save additional state information, you should always call the superclass implementation of onRestoreInstanceState() if you override it, so 


Coordinating activities

When one activity starts another, they both expirence lifecycle transitions. The first activity pauses and stops(though, it won't stop if it's visible in the backgound), while the other activity is created. In case these activities share data saved to disc or elsewhere, it's important to understand that the first activity is not completely stopped before the second one is created. Rather, the process of starting the second one overlaps with the process of stopping the first one.


The order of lifecycle callbacks is well defined, particularly when the two activities are in the same process and one is starting the other. Here's the order of operations that occur when Activity A starts Activity B:

1.Activity A's onPause() method executes.

2.Activity B's onCreate(), onStart(), and onResume() methods execute in sequence.(Activity B now has user focus.)

3.Then, if Activity A is no longer visible on screen, its onStop() method executes.


This predictable sequence of lifecycle callbacks allows you to manage the transition of information from one activity to another. For example, if you must write to a database when the first activity stops so that the following activity can read it, then you should write to the database during onPause() instead of during onStop().










  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值