Activity

1. Activity切换

Each time a new activity starts, the previous activity is stopped, but the system preserves the activity in a stack (the "back stack"). 

新的activty开启时,先前的activty就停止并且被压入栈中。

 

2. Activity中的回调函数

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 change. 

activty开启旧activty停止时,这个状态变化的过程,通过activty的生命周期的回调方法通知。

有数个这样的回调方法activity可以接收。(在触发这些回调函数是,你可以完成当前状态的一些合适的工作)

 

3. 自己定义的activity要继承Activity类

To create an activity, you must create a subclass of Activity (or an existing subclass of it). 

创建一个activity,你需要创建一个Activity的子类

In your subclass, you need to implement callback methods that the system calls when the activity transitions between various states of its lifecycle 

在子类中你需要实现那些,当activity在多样的生命周期中循环传输时,系统调用的回调方法

 

4. 两个重要的回调方法

 

onCreate()

    You must implement this method. The system calls this when creating your activity. 

    Within your implementation, you should initialize the essential co    mponents of your activity. 

    Most importantly, this is where you must call setContentView() to define the layout for the activity's user interface.

    特别重要的,你必须调用setContentView()定义这个activity用户界面的布局

onPause()

    The system calls this method 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).

 

5. 在manifest中声明activity

You must declare your activity in the manifest file in order for it to be accessible to the system.

 

6.  使用<intent filters>

An <activity> element can also specify various intent filters—using the <intent-filter> element—in order to declare how other application components may activate it.

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

Activities that you don't want to make available to other applications should have no intent filters and you can start them yourself using explicit intents

 

7. 开启另一个Activity

You can start another activity by calling startActivity(), passing it an Intent that describes the activity you want to start. 

    The intent specifies either the exact activity you want to start 

    or describes the type of action you want to perform (and the system selects the appropriate activity for you, which can even be from a different application).

    An intent can also carry small amounts of data to be used by the activity that is started.

    执行当前或其他应用中的activity,

 

 

For example, here's how one activity starts another activity named SignInActivity:

Intent intent =newIntent(this,SignInActivity.class);
startActivity(intent);

 

一个intent可携带少量数据

 

Intent intent =newIntent(Intent.ACTION_SEND);
intent.putExtra(Intent.EXTRA_EMAIL, recipientArray);
startActivity(intent);

 

 

8. 开启另一个Activity并且返回值

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.

 

假设:我这里有两个Activity:A和B,从A中向B中传递数据的时候采用的是Bundle封装数据,然后从A中跳转到B中,当B有需求将数据封装起来回传给A并跳转回A。那么A中接收数据时还要先判断Bundle是否为空,因为第一次访问A的时候(即B还没有回传的时候),Bundle是为空的,这样显然是比较麻烦的,不明智的做法。

还好startActivityForResult来做跳转给了我们更好的解决办法。

a.跳转的时候不是采用startActivity(intent) 这个方法,而是startActivityForResult(intent, 0)。

privatevoid pickContact(){// Create an intent to "pick" a contact, as defined by the content provider URIIntent intent =newIntent(Intent.ACTION_PICK,Contacts.CONTENT_URI);
    startActivityForResult(intent, PICK_CONTACT_REQUEST);}
// 这里采用startActivityForResult来做跳转,此处的0为一个依据,可以写其他的值,但一定要>=0
// If >= 0, this code will be returned in onActivityResult() when the activity exits.

 

b.重写onActivityResult方法,用来接收B回传的数据。

@Overrideprotectedvoid onActivityResult(int requestCode,int resultCode,Intent data){// If the request went well (OK) and the request was PICK_CONTACT_REQUESTif(resultCode ==Activity.RESULT_OK && requestCode == PICK_CONTACT_REQUEST){// Perform a query to the contact's content provider for the contact's nameCursor cursor = getContentResolver().query(data.getData(),newString[]{Contacts.DISPLAY_NAME},null,null,null);if(cursor.moveToFirst()){// True if the cursor is not emptyint columnIndex = cursor.getColumnIndex(Contacts.DISPLAY_NAME);String name = cursor.getString(columnIndex);// Do something with the selected contact's name...}}}

 

c.在B中回传数据时采用setResult方法,并且之后要调用finish方法。

setResult(RESULT_OK, intent); //intent为A传来的带有Bundle的intent,当然也可以自己定义新的Bundle
finish();//此处一定要调用finish()方法

 

9.Activity的生命周期

 

10.生命周期有关的回调方法

 

11.一个活动的三种基本状态

 

An activity can exist in essentially three states:

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 is 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 "background"). 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.

 

 

12.保存活动状态

However, when the system destroys an activity in order to recover memory, the Activity object is destroyed, so the system cannot simply resume it with its state intact. Instead, the system must recreate the Activity object if the user navigates back to it. Yet, the user is unaware that the system destroyed the activity and recreated it and, thus, probably expects the activity to be exactly as it was. In this situation, you can ensure that important information about the activity state is preserved by implementing an additional callback method that allows you to save information about the state of your activity: onSaveInstanceState().

The system calls onSaveInstanceState() before making the activity vulnerable to destruction. The system passes this method a Bundle in which you can save state information about the activity as name-value pairs, 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 bothonCreate() 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 Bundlepassed to you is null (which is the case when the activity is created for the first time).

 

他们比较常用到的地方是 Sensor、Land和Port布局的自动切换,比如解决横屏和竖屏切换带来的数据被置空或者说onCreate被重复调用问题,其实Android提供的onSaveInstanceState方法可以保存当前的窗口状态在即将布局切换前或当前Activity被推入历史栈,其实布局切换也调用过onPause所以被推入Activity的history stack,如果我们的Activity在后台没有因为运行内存吃紧被清理,则切换回时会触发onRestoreInstanceState方法。

 这两个方法中参数均为Bundle,可以存放类似 SharedPreferences 的数据,所以使用它们作为当前窗口的状态保存是比较合适的。实际使用代码

@Override
  protected void onSaveInstanceState(Bundle outState){
             outState.putString("lastPath", "/sdcard/android123/cwj/test");
   }


@Override 
public void onRestoreInstanceState(Bundle savedInstanceState) { 
super.onRestoreInstanceState(savedInstanceState);

String cwjString = savedInstanceState.getString("lastPath"); 
}

 

 

14. 三种角度,三个生命周期

 

 

Taken together, these methods define the entire lifecycle of an activity. By implementing these methods, you can monitor three nested loops in the activity lifecycle:

  • The entire lifetime of an activity happens between the call to onCreate() and the call to onDestroy(). Your activity should perform setup of "global" state (such as defining layout) in onCreate(), and release all remaining resources in onDestroy(). For example, if your activity has a thread running in the background to download data from the network, it might create that thread in onCreate() and then stop the thread inonDestroy().
  • The visible lifetime of an activity happens between the call to onStart() and the call to onStop(). During this time, the user can see the activity on-screen and interact with it. For example, onStop() is called when a new activity starts and this one is no longer visible. Between these two methods, you can maintain resources that are needed to show the activity to the user. For example, you can register a BroadcastReceiver inonStart() to monitor changes that impact your UI, and unregister it in onStop() when the user can no longer see what you are displaying. The system might call onStart() and onStop() multiple times during the entire lifetime of the activity, as the activity alternates between being visible and hidden to the user.

  • The foreground lifetime of an activity happens between the call to onResume() and the call to onPause(). During this time, the activity is in front of all other activities on screen and has user input focus. An activity can frequently transition in and out of the foreground—for example, onPause() is called when the device goes to sleep or when a dialog appears. Because this state can transition often, the code in these two methods should be fairly lightweight in order to avoid slow transitions that make the user wait.

 

Activity的完整生命周期自第一次调用onCreate()开始,直至调用onDestroy()为止。Activity在onCreate()中设置所有“全局”状态以完成初始化,而在onDestroy()中释放所有系统资源。例如,如果Activity有一个线程在后台运行从网络下载数据,它会在onCreate()创建线程,而在 onDestroy()销毁线程。 

 

 Activity的可视生命周期自onStart()调用开始直到相应的onStop()调用结束。在此期间,用户可以在屏幕上看到Activity,尽管它也许并不是位于前台或者也不与用户进行交互。在这两个方法之间,我们可以保留用来向用户显示这个Activity所需的资源。例如,当用户不再看见我们显示的内容时,我们可以在onStart()中注册一个BroadcastReceiver来监控会影响UI的变化,而在onStop()中来注消。onStart() 和 onStop() 方法可以随着应用程序是否为用户可见而被多次调用。 

 

 Activity的前台生命周期自onResume()调用起,至相应的onPause()调用为止。在此期间,Activity位于前台最上面并与用户进行交互。Activity会经常在暂停和恢复之间进行状态转换——例如当设备转入休眠状态或者有新的Activity启动时,将调用onPause() 方法。当Activity获得结果或者接收到新的Intent时会调用onResume() 方法。关于前台生命周期循环的例子请见PPT下方备注栏。

 

 

 

 

 

 

 

 

 

 

 

posted @ 2012-07-27 16:16  疾行の亚索  阅读(124)  评论(0)    收藏  举报