Activity 二主要介绍Activity中的成员函数,顺序是按照SDK顺序来排布的,但是我是从后往前看的,所以前面部分比较简单的函数并没有多做介绍。。

Since: API Level 1

Use with setDefaultKeyMode(int) to launch the dialer during default key handling.

See Also

· setDefaultKeyMode(int)

Constant Value: 1 (0x00000001)

public static final int DEFAULT_KEYS_DISABLE

Since: API Level 1

Use with setDefaultKeyMode(int) to turn off default handling of keys.

See Also

· setDefaultKeyMode(int)

Constant Value: 0 (0x00000000)

public static final int DEFAULT_KEYS_SEARCH_GLOBAL

Since: API Level 1

Use with setDefaultKeyMode(int) to specify that unhandled keystrokes will start a global search (typically web search, but some platforms may define alternate methods for global search)

See android.app.SearchManager for more details.

See Also

· setDefaultKeyMode(int)

Constant Value: 4 (0x00000004)

public static final int DEFAULT_KEYS_SEARCH_LOCAL

Since: API Level 1

Use with setDefaultKeyMode(int) to specify that unhandled keystrokes will start an application-defined search. (If the application or activity does not actually define a search, the the keys will be ignored.)

See android.app.SearchManager for more details.

See Also

· setDefaultKeyMode(int)

Constant Value: 3 (0x00000003)

public static final int DEFAULT_KEYS_SHORTCUT

Since: API Level 1

Use with setDefaultKeyMode(int) to execute a menu shortcut in default key handling.

That is, the user does not need to hold down the menu key to execute menu shortcuts.

See Also

· setDefaultKeyMode(int)

Constant Value: 2 (0x00000002)

protected static final int[] FOCUSED_STATE_SET

Since: API Level 1

public static final int RESULT_CANCELED

Since: API Level 1

Standard activity result: operation canceled.

Constant Value: 0 (0x00000000)

public static final int RESULT_FIRST_USER

Since: API Level 1

Start of user-defined activity results.

Constant Value: 1 (0x00000001)

public static final int RESULT_OK

Since: API Level 1

Standard activity result: operation succeeded.

Constant Value: -1 (0xffffffff)

Public Constructors

public Activity ()

Since: API Level 1

Public Methods

public void addContentView (View view, ViewGroup.LayoutParams params)

Since: API Level 1

Add an additional content view to the activity. Added after any existing ones in the activity -- existing views are NOT removed.

Parameters

view

The desired content to display.

params

Layout parameters for the view.

public void closeContextMenu ()

Since: API Level 3

Programmatically closes the most recently opened context menu, if showing.

public void closeOptionsMenu ()

Since: API Level 1

Progammatically closes the options menu. If the options menu is already closed, this method does nothing.

public PendingIntent createPendingResult (int requestCode, Intent data, int flags)

Since: API Level 1

Create a new PendingIntent object which you can hand to others for them to use to send result data back to your onActivityResult(int, int, Intent) callback. The created object will be either one-shot (becoming invalid after a result is sent back) or multiple (allowing any number of results to be sent through it).

Parameters

requestCode

Private request code for the sender that will be associated with the result data when it is returned. The sender can not modify this value, allowing you to identify incoming results.

data

Default data to supply in the result, which may be modified by the sender.

flags

May be PendingIntent.FLAG_ONE_SHOT, PendingIntent.FLAG_NO_CREATE, PendingIntent.FLAG_CANCEL_CURRENT, PendingIntent.FLAG_UPDATE_CURRENT, or any of the flags as supported by Intent.fillIn() to control which unspecified parts of the intent that can be supplied when the actual send happens.

Returns

· Returns an existing or new PendingIntent matching the given parameters. May return null only if PendingIntent.FLAG_NO_CREATE has been supplied.

See Also

· PendingIntent

public final void dismissDialog (int id)

Since: API Level 1

Dismiss a dialog that was previously shown via showDialog(int).

Parameters

id

The id of the managed dialog.

Throws

IllegalArgumentException

if the id was not previously shown via showDialog(int).

See Also

· onCreateDialog(int)

· onPrepareDialog(int, Dialog)

· showDialog(int)

· removeDialog(int)

public boolean dispatchKeyEvent (KeyEvent event)

Since: API Level 1

Called to process key events. You can override this to intercept all key events before they are dispatched to the window. Be sure to call this implementation for key events that should be handled normally.

Parameters

event

The key event.

Returns

· boolean Return true if this event was consumed.

public boolean dispatchPopulateAccessibilityEvent (AccessibilityEvent event)

Since: API Level 4

Called to process population of AccessibilityEvents.

Parameters

event

The event.

Returns

· boolean Return true if event population was completed.

public boolean dispatchTouchEvent (MotionEvent ev)

Since: API Level 1

Called to process touch screen events. You can override this to intercept all touch screen events before they are dispatched to the window. Be sure to call this implementation for touch screen events that should be handled normally.

Parameters

ev

The touch screen event.

Returns

· boolean Return true if this event was consumed.

public boolean dispatchTrackballEvent (MotionEvent ev)

Since: API Level 1

Called to process trackball events. You can override this to intercept all trackball events before they are dispatched to the window. Be sure to call this implementation for trackball events that should be handled normally.

Parameters

ev

The trackball event.

Returns

· boolean Return true if this event was consumed.

public View findViewById (int id)

Since: API Level 1

Finds a view that was identified by the id attribute from the XML that was processed in onCreate(Bundle).

Returns

· The view if found or null otherwise.

public void finish ()

Since: API Level 1

Call this when your activity is done and should be closed. The ActivityResult is propagated back to whoever launched you via onActivityResult().

public void finishActivity (int requestCode)

Since: API Level 1

Force finish another activity that you had previously started with startActivityForResult(Intent, int).

Parameters

requestCode

The request code of the activity that you had given to startActivityForResult(). If there are multiple activities started with this request code, they will all be finished.

public void finishActivityFromChild (Activity child, int requestCode)

Since: API Level 1

This is called when a child activity of this one calls its finishActivity().

Parameters

child

The activity making the call.

requestCode

Request code that had been used to start the activity.

public void finishFromChild (Activity child)

Since: API Level 1

This is called when a child activity of this one calls its finish() method. The default implementation simply calls finish() on this activity (the parent), finishing the entire group.

Parameters

child

The activity making the call.

See Also

· finish()

public final Application getApplication ()

Since: API Level 1

Return the application that owns this activity.

public ComponentName getCallingActivity ()

Since: API Level 1

Return the name of the activity that invoked this activity. This is who the data in setResult() will be sent to. You can use this information to validate that the recipient is allowed to receive the data.

Note: if the calling activity is not expecting a result (that is it did not use the startActivityForResult(Intent, int) form that includes a request code), then the calling package will be null.

Returns

· String The full name of the activity that will receive your reply, or null if none.

public String getCallingPackage ()

Since: API Level 1

Return the name of the package that invoked this activity. This is who the data in setResult() will be sent to. You can use this information to validate that the recipient is allowed to receive the data.

Note: if the calling activity is not expecting a result (that is it did not use the startActivityForResult(Intent, int) form that includes a request code), then the calling package will be null.

Returns

· The package of the activity that will receive your reply, or null if none.

public int getChangingConfigurations ()

Since: API Level 1

If this activity is being destroyed because it can not handle a configuration parameter being changed (and thus its onConfigurationChanged(Configuration) method is not being called), then you can use this method to discover the set of changes that have occurred while in the process of being destroyed. Note that there is no guarantee that these will be accurate (other changes could have happened at any time), so you should only use this as an optimization hint.

不可靠的方法。一般在有配置变化时,默认会销毁当前的activity.可以从此方法来查看有什么配置变化。

Returns

· Returns a bit field of the configuration parameters that are changing, as defined by the Configuration class.

public ComponentName getComponentName ()

Since: API Level 1

Returns complete component name of this activity.

Returns

· Returns the complete component name for this activity

public View getCurrentFocus ()

Since: API Level 1

Calls getCurrentFocus() on the Window of this Activity to return the currently focused view.

Returns

· View The current View with focus or null.

See Also

· getWindow()

· getCurrentFocus()

public static long getInstanceCount ()

Since: API Level 1

public Intent getIntent ()

Since: API Level 1

Return the intent that started this activity.

public Object getLastNonConfigurationInstance ()

Since: API Level 1

Retrieve the non-configuration instance data that was previously returned by onRetainNonConfigurationInstance(). This will be available from the initial onCreate(Bundle) and onStart() calls to the new instance, allowing you to extract any useful dynamic state from the previous instance.

Note that the data you retrieve here should only be used as an optimization for handling configuration changes. You should always be able to handle getting a null pointer back, and an activity must still be able to restore itself to its previous state (through the normal onSaveInstanceState(Bundle) mechanism) even if this function returns null.

Returns

· Returns the object previously returned by onRetainNonConfigurationInstance().

public LayoutInflater getLayoutInflater ()

Since: API Level 1

Convenience for calling getLayoutInflater().

public String getLocalClassName ()

Since: API Level 1

Returns class name for this activity with the package prefix removed. This is the default name used to read and write settings.

Returns

· The local class name.

public MenuInflater getMenuInflater ()

Since: API Level 1

Returns a MenuInflater with this context.

public final Activity getParent ()

Since: API Level 1

Return the parent activity if this view is an embedded child.

public SharedPreferences getPreferences (int mode)

Since: API Level 1

Retrieve a SharedPreferences object for accessing preferences that are private to this activity. This simply calls the underlying getSharedPreferences(String, int) method by passing in this activity's class name as the preferences name.

获取user Preferences的接口,

Parameters

mode

Operating mode. Use MODE_PRIVATE for the default operation, MODE_WORLD_READABLE and MODE_WORLD_WRITEABLE to control permissions.

Returns

· Returns the single SharedPreferences instance that can be used to retrieve and modify the preference values.

public int getRequestedOrientation ()

Since: API Level 1

Return the current requested orientation of the activity. This will either be the orientation requested in its component's manifest, or the last requested orientation given to setRequestedOrientation(int).

Returns

· Returns an orientation constant as used in ActivityInfo.screenOrientation.

public Object getSystemService (String name)

Since: API Level 1

Return the handle to a system-level service by name. The class of the returned object varies by the requested name. Currently available names are:

WINDOW_SERVICE ("window")

The top-level window manager in which you can place custom windows. The returned object is a WindowManager.

LAYOUT_INFLATER_SERVICE ("layout_inflater")

A LayoutInflater for inflating layout resources in this context.

ACTIVITY_SERVICE ("activity")

A ActivityManager for interacting with the global activity state of the system.

POWER_SERVICE ("power")

A PowerManager for controlling power management.

ALARM_SERVICE ("alarm")

A AlarmManager for receiving intents at the time of your choosing.

NOTIFICATION_SERVICE ("notification")

A NotificationManager for informing the user of background events.

KEYGUARD_SERVICE ("keyguard")

A KeyguardManager for controlling keyguard.

LOCATION_SERVICE ("location")

A LocationManager for controlling location (e.g., GPS) updates.

SEARCH_SERVICE ("search")

A SearchManager for handling search.

VIBRATOR_SERVICE ("vibrator")

A Vibrator for interacting with the vibrator hardware.

CONNECTIVITY_SERVICE ("connection")

A ConnectivityManager for handling management of network connections.

WIFI_SERVICE ("wifi")

A WifiManager for management of Wi-Fi connectivity.

INPUT_METHOD_SERVICE ("input_method")

An InputMethodManager for management of input methods.

Note: System services obtained via this API may be closely associated with the Context in which they are obtained from. In general, do not share the service objects between various different contexts (Activities, Applications, Services, Providers, etc.)

Parameters

name

The name of the desired service.

Returns

· The service or null if the name does not exist.

public int getTaskId ()

Since: API Level 1

Return the identifier of the task this activity is in. This identifier will remain the same for the lifetime of the activity.

Returns

· Task identifier, an opaque integer.

public final CharSequence getTitle ()

Since: API Level 1

public final int getTitleColor ()

Since: API Level 1

public final int getVolumeControlStream ()

Since: API Level 1

Gets the suggested audio stream whose volume should be changed by the harwdare volume controls.

Returns

· The suggested audio stream type whose volume should be changed by the hardware volume controls.

See Also

· setVolumeControlStream(int)

public int getWallpaperDesiredMinimumHeight ()

Since: API Level 1

This method is deprecated.
Use
WallpaperManager.getDesiredMinimumHeight() instead.

public int getWallpaperDesiredMinimumWidth ()

Since: API Level 1

This method is deprecated.
Use
WallpaperManager.getDesiredMinimumWidth() instead.

public Window getWindow ()

Since: API Level 1

Retrieve the current Window for the activity. This can be used to directly access parts of the Window API that are not available through Activity/Screen.

Returns

· Window The current window, or null if the activity is not visual.

public WindowManager getWindowManager ()

Since: API Level 1

Retrieve the window manager for showing custom windows.

public boolean hasWindowFocus ()

Since: API Level 3

Returns true if this activity's main window currently has window focus. Note that this is not the same as the view itself having focus.

Returns

· True if this activity's main window currently has window focus.

See Also

· onWindowAttributesChanged(android.view.WindowManager.LayoutParams)

public final boolean isChild ()

Since: API Level 1

Is this activity embedded inside of another activity?

public boolean isFinishing ()

Since: API Level 1

Check to see whether this activity is in the process of finishing, either because you called finish() on it or someone else has requested that it finished. This is often used in onPause() to determine whether the activity is simply pausing or completely finishing.

Returns

· If the activity is finishing, returns true; else returns false.

See Also

· finish()

public boolean isTaskRoot ()

Since: API Level 1

Return whether this activity is the root of a task. The root is the first activity in a task.

Returns

· True if this is the root activity, else false.

public final Cursor managedQuery (Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder)

Since: API Level 1

Wrapper around query(android.net.Uri, String[], String, String[], String) that gives the resulting Cursor to call startManagingCursor(Cursor) so that the activity will manage its lifecycle for you.

Parameters

uri

The URI of the content provider to query.

projection

List of columns to return.

selection

SQL WHERE clause.

selectionArgs

The arguments to selection, if any ?s are pesent

sortOrder

SQL ORDER BY clause.

Returns

· The Cursor that was returned by query().

See Also

· query(android.net.Uri, String[], String, String[], String)

· startManagingCursor(Cursor)

public boolean moveTaskToBack (boolean nonRoot)

Since: API Level 1

Move the task containing this activity to the back of the activity stack. The activity's order within the task is unchanged.

Parameters

nonRoot

If false then this only works if the activity is the root of a task; if true it will work for any activity in a task.

Returns

· If the task was moved (or it was already at the back) true is returned, else false.

public void onAttachedToWindow ()

Since: API Level 5

Called when the main window associated with the activity has been attached to the window manager. See View.onAttachedToWindow() for more information.

See Also

· onAttachedToWindow()

public void onBackPressed ()

Since: API Level 5

Called when the activity has detected the user's press of the back key. The default implementation simply finishes the current activity, but you can override this to do whatever you want.

back键按了以后,会调用此方法,默认是finish当前的Activity.

public void onConfigurationChanged (Configuration newConfig)

Since: API Level 1

Called by the system when the device configuration changes while your activity is running. Note that this will only be called if you have selected configurations you would like to handle with the configChanges attribute in your manifest. If any configuration change occurs that is not selected to be reported by that attribute, then instead of reporting it the system will stop and restart the activity (to have it launched with the new configuration).

注意这个方法引起的activity的重新生成

At the time that this function has been called, your Resources object will have been updated to return resource values matching the new configuration.

Parameters

newConfig

The new device configuration.

public void onContentChanged ()

Since: API Level 1

This hook is called whenever the content view of the screen changes (due to a call to Window.setContentView or Window.addContentView).

public boolean onContextItemSelected (MenuItem item)

Since: API Level 1

This hook is called whenever an item in a context menu is selected. The default implementation simply returns false to have the normal processing happen (calling the item's Runnable or sending a message to its Handler as appropriate). You can use this method for any items for which you would like to do processing without those other facilities.

Use getMenuInfo() to get extra information set by the View that added this menu item.

Derived classes should call through to the base class for it to perform the default menu handling.

Parameters

item

The context menu item that was selected.

Returns

· boolean Return false to allow normal context menu processing to proceed, true to consume it here.

public void onContextMenuClosed (Menu menu)

Since: API Level 1

This hook is called whenever the context menu is being closed (either by the user canceling the menu with the back/menu button, or when an item is selected).

Parameters

menu

The context menu that is being closed.

public void onCreateContextMenu (ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo)

Since: API Level 1

Called when a context menu for the view is about to be shown. Unlike onCreateOptionsMenu(Menu), this will be called every time the context menu is about to be shown and should be populated for the view (or item inside the view for AdapterView subclasses, this can be found in the menuInfo)).

Use onContextItemSelected(android.view.MenuItem) to know when an item has been selected.

It is not safe to hold onto the context menu after this method returns. Called when the context menu for this view is being built. It is not safe to hold onto the menu after this method returns.

Parameters

menu

The context menu that is being built

v

The view for which the context menu is being built

menuInfo

Extra information about the item for which the context menu should be shown. This information will vary depending on the class of v.

public CharSequence onCreateDescription ()

Since: API Level 1

Generate a new description for this activity. This method is called before pausing the activity and can, if desired, return some textual description of its current state to be displayed to the user.

The default implementation returns null, which will cause you to inherit the description from the previous activity. If all activities return null, generally the label of the top activity will be used as the description.

Returns

· A description of what the user is doing. It should be short and sweet (only a few words).

See Also

· onCreateThumbnail(Bitmap, Canvas)

· onSaveInstanceState(Bundle)

· onPause()

public boolean onCreateOptionsMenu (Menu menu)

Since: API Level 1

Initialize the contents of the Activity's standard options menu. You should place your menu items in to menu.

This is only called once, the first time the options menu is displayed. To update the menu every time it is displayed, see onPrepareOptionsMenu(Menu).

The default implementation populates the menu with standard system menu items. These are placed in the CATEGORY_SYSTEM group so that they will be correctly ordered with application-defined menu items. Deriving classes should always call through to the base implementation.

You can safely hold on to menu (and any items created from it), making modifications to it as desired, until the next time onCreateOptionsMenu() is called.

可以安全的的保持menuonCrateOptionMenu创建的对象),直到下次此函数的调用,注意这个方法和onCreateContectMenu的区别。

When you add items to the menu, you can implement the Activity's onOptionsItemSelected(MenuItem) method to handle them there.

Parameters

menu

The options menu in which you place your items.

Returns

· You must return true for the menu to be displayed; if you return false it will not be shown.

See Also

· onPrepareOptionsMenu(Menu)

· onOptionsItemSelected(MenuItem)

public boolean onCreatePanelMenu (int featureId, Menu menu)

Since: API Level 1

Default implementation of onCreatePanelMenu(int, Menu) for activities. This calls through to the new onCreateOptionsMenu(Menu) method for the FEATURE_OPTIONS_PANEL panel, so that subclasses of Activity don't need to deal with feature codes.

Parameters

featureId

The panel being created.

menu

The menu inside the panel.

Returns

· boolean You must return true for the panel to be displayed; if you return false it will not be shown.

public View onCreatePanelView (int featureId)

Since: API Level 1

Default implementation of onCreatePanelView(int) for activities. This simply returns null so that all panel sub-windows will have the default menu behavior.

Parameters

featureId

Which panel is being created.

Returns

· view The top-level view to place in the panel.

public boolean onCreateThumbnail (Bitmap outBitmap, Canvas canvas)

Since: API Level 1

Generate a new thumbnail for this activity. This method is called before pausing the activity, and should draw into outBitmap the imagery for the desired thumbnail in the dimensions of that bitmap. It can use the given canvas, which is configured to draw into the bitmap, for rendering if desired.

The default implementation renders the Screen's current view hierarchy into the canvas to generate a thumbnail.

If you return false, the bitmap will be filled with a default thumbnail.

Parameters

outBitmap

The bitmap to contain the thumbnail.

canvas

Can be used to render into the bitmap.

Returns

· Return true if you have drawn into the bitmap; otherwise after you return it will be filled with a default thumbnail.

See Also

· onCreateDescription()

· onSaveInstanceState(Bundle)

· onPause()

public View onCreateView (String name, Context context, AttributeSet attrs)

Since: API Level 1

Stub implementation of onCreateView(String, Context, AttributeSet) used when inflating with the LayoutInflater returned by getSystemService(String). This implementation simply returns null for all view names.

Parameters

name

Tag name to be inflated.

context

The context the view is being created in.

attrs

Inflation attributes as specified in XML file.

Returns

· View Newly created view. Return null for the default behavior.

See Also

· createView(String, String, AttributeSet)

· getLayoutInflater()

public void onDetachedFromWindow ()

Since: API Level 5

Called when the main window associated with the activity has been detached from the window manager. See View.onDetachedFromWindow() for more information.

activity和其关联的window之间的关联关系解除时将会调用此函数。

See Also

· onDetachedFromWindow()

public boolean onKeyDown (int keyCode, KeyEvent event)

Since: API Level 1

Called when a key was pressed down and not handled by any of the views inside of the activity. So, for example, key presses while the cursor is inside a TextView will not trigger the event (unless it is a navigation to another object) because TextView handles its own key presses.

If the focused view didn't want this event, this method is called.

The default implementation takes care of KEYCODE_BACK by calling onBackPressed(), though the behavior varies based on the application compatibility mode: for ECLAIR or later applications, it will set up the dispatch to call onKeyUp(int, KeyEvent) where the action will be performed; for earlier applications, it will perform the action immediately in on-down, as those versions of the platform behaved.

Other additional default key handling may be performed if configured with setDefaultKeyMode(int).

Parameters

keyCode

The value in event.getKeyCode().

event

Description of the key event.

Returns

· Return true to prevent this event from being propagated further, or false to indicate that you have not handled this event and it should continue to be propagated.

See Also

· onKeyUp(int, KeyEvent)

· KeyEvent

public boolean onKeyLongPress (int keyCode, KeyEvent event)

Since: API Level 5

Default implementation of KeyEvent.Callback.onKeyLongPress(): always returns false (doesn't handle the event).

Parameters

keyCode

The value in event.getKeyCode().

event

Description of the key event.

Returns

· If you handled the event, return true. If you want to allow the event to be handled by the next receiver, return false.

public boolean onKeyMultiple (int keyCode, int repeatCount, KeyEvent event)

Since: API Level 1

Default implementation of KeyEvent.Callback.onKeyMultiple(): always returns false (doesn't handle the event).

Parameters

keyCode

The value in event.getKeyCode().

repeatCount

Number of pairs as returned by event.getRepeatCount().

event

Description of the key event.

Returns

· If you handled the event, return true. If you want to allow the event to be handled by the next receiver, return false.

public boolean onKeyUp (int keyCode, KeyEvent event)

Since: API Level 1

Called when a key was released and not handled by any of the views inside of the activity. So, for example, key presses while the cursor is inside a TextView will not trigger the event (unless it is a navigation to another object) because TextView handles its own key presses.

The default implementation handles KEYCODE_BACK to stop the activity and go back.

Parameters

keyCode

The value in event.getKeyCode().

event

Description of the key event.

Returns

· Return true to prevent this event from being propagated further, or false to indicate that you have not handled this event and it should continue to be propagated.

See Also

· onKeyDown(int, KeyEvent)

· KeyEvent

public void onLowMemory ()

Since: API Level 1

This is called when the overall system is running low on memory, and would like actively running process to try to tighten their belt. While the exact point at which this will be called is not defined, generally it will happen around the time all background process have been killed, that is before reaching the point of killing processes hosting service and foreground UI that we would like to avoid killing.

Applications that want to be nice can implement this method to release any caches or other unnecessary resources they may be holding on to. The system will perform a gc for you after returning from this method.

public boolean onMenuItemSelected (int featureId, MenuItem item)

Since: API Level 1

Default implementation of onMenuItemSelected(int, MenuItem) for activities. This calls through to the new onOptionsItemSelected(MenuItem) method for the FEATURE_OPTIONS_PANEL panel, so that subclasses of Activity don't need to deal with feature codes.

Parameters

featureId

The panel that the menu is in.

item

The menu item that was selected.

Returns

· boolean Return true to finish processing of selection, or false to perform the normal menu handling (calling its Runnable or sending a Message to its target Handler).

public boolean onMenuOpened (int featureId, Menu menu)

Since: API Level 1

Called when a panel's menu is opened by the user. This may also be called when the menu is changing from one type to another (for example, from the icon menu to the expanded menu).

Parameters

featureId

The panel that the menu is in.

menu

The menu that is opened.

Returns

· The default implementation returns true.

public boolean onOptionsItemSelected (MenuItem item)

Since: API Level 1

This hook is called whenever an item in your options menu is selected. The default implementation simply returns false to have the normal processing happen (calling the item's Runnable or sending a message to its Handler as appropriate). You can use this method for any items for which you would like to do processing without those other facilities.

Derived classes should call through to the base class for it to perform the default menu handling.

Parameters

item

The menu item that was selected.

Returns

· boolean Return false to allow normal menu processing to proceed, true to consume it here.

See Also

· onCreateOptionsMenu(Menu)

public void onOptionsMenuClosed (Menu menu)

Since: API Level 1

This hook is called whenever the options menu is being closed (either by the user canceling the menu with the back/menu button, or when an item is selected).

optionMenu close关闭时会调用此方法。一般是用户按了menu键或者back键,或选择了某一个item.

Parameters

menu

The options menu as last shown or first initialized by onCreateOptionsMenu().

public void onPanelClosed (int featureId, Menu menu)

Since: API Level 1

Default implementation of onPanelClosed(int, Menu) for activities. This calls through to onOptionsMenuClosed(Menu) method for the FEATURE_OPTIONS_PANEL panel, so that subclasses of Activity don't need to deal with feature codes. For context menus (FEATURE_CONTEXT_MENU), the onContextMenuClosed(Menu) will be called.

Parameters

featureId

The panel that is being displayed.

menu

If onCreatePanelView() returned null, this is the Menu being displayed in the panel.

public boolean onPrepareOptionsMenu (Menu menu)

Since: API Level 1

Prepare the Screen's standard options menu to be displayed. This is called right before the menu is shown, every time it is shown. You can use this method to efficiently enable/disable items or otherwise dynamically modify the contents.

The default implementation updates the system menu items based on the activity's state. Deriving classes should always call through to the base class implementation.

在显示optionMenu之前可以更改其显示,因为ActivityonCreateOptionMenuactivity声明周期内只会调用一次,所以有些初始化动作需要在这个函数里面进行处理。

Parameters

menu

The options menu as last shown or first initialized by onCreateOptionsMenu().

Returns

· You must return true for the menu to be displayed; if you return false it will not be shown.

See Also

· onCreateOptionsMenu(Menu)

public boolean onPreparePanel (int featureId, View view, Menu menu)

Since: API Level 1

Default implementation of onPreparePanel(int, View, Menu) for activities. This calls through to the new onPrepareOptionsMenu(Menu) method for the FEATURE_OPTIONS_PANEL panel, so that subclasses of Activity don't need to deal with feature codes.

Parameters

featureId

The panel that is being displayed.

view

The View that was returned by onCreatePanelView().

menu

If onCreatePanelView() returned null, this is the Menu being displayed in the panel.

Returns

· boolean You must return true for the panel to be displayed; if you return false it will not be shown.

public Object onRetainNonConfigurationInstance ()

Since: API Level 1

Called by the system, as part of destroying an activity due to a configuration change, when it is known that a new instance will immediately be created for the new configuration. You can return any object you like here, including the activity instance itself, which can later be retrieved by calling getLastNonConfigurationInstance() in the new activity instance.

This function is called purely as an optimization, and you must not rely on it being called. When it is called, a number of guarantees will be made to help optimize configuration switching:

· The function will be called between onStop() and onDestroy().

· A new instance of the activity will always be immediately created after this one's onDestroy() is called.

· The object you return here will always be available from the getLastNonConfigurationInstance() method of the following activity instance as described there.

These guarantees are designed so that an activity can use this API to propagate extensive state from the old to new activity instance, from loaded bitmaps, to network connections, to evenly actively running threads. Note that you should not propagate any data that may change based on the configuration, including any data loaded from resources such as strings, layouts, or drawables.

这个没有用到过,到网上搜索了一个哥们的解释

onRetainNonConfigurationInstance()

Device configuration发生改变时,将伴随Destroying被系统调用。通过这个方法可以像onSaveInstanceState()的方法一样保留变化前的Activity State,最大的不同在于这个方法可以返回一个包含有状态信息的Object,其中甚至可以包含Activity Instance本身。新创建的Activity可以继承大量来至于Parent Activity State信息。

用这个方法保存Activity State后,通过getLastNonConfigurationInstance()在新的Activity Instance中恢复原有状态。

这个方法最大的好处是:

* Activity曾经通过某个网络资源得到一些图片或者视频信息,那么当再次恢复后,无需重新通过原始资源地址获取,可以快速的加载整个Activity状态信息。

* Activity包含有许多线程时,在变化后依然可以持有原有线程,无需通过重新创建进程恢复原有状态。

* Activity包含某些Connection Instance时,同样可以在整个变化过程中保持连接状态。

下边是需要特别注意的几点:

* onRetainNonConfigurationInstance()onSaveInstanceState()之后被调用。

* 调用顺序同样介于onStop() onDestroy()之间。

本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/li_guotao/archive/2010/04/12/5474880.aspx

Returns

· Return any Object holding the desired state to propagate to the next activity instance.

public boolean onSearchRequested ()

Since: API Level 1

This hook is called when the user signals the desire to start a search.

You can use this function as a simple way to launch the search UI, in response to a menu item, search button, or other widgets within your activity. Unless overidden, calling this function is the same as calling startSearch(null, false, null, false), which launches search for the current activity as specified in its manifest, see SearchManager.

You can override this function to force global search, e.g. in response to a dedicated search key, or to block search entirely (by simply returning false).

Returns

· Returns true if search launched, and false if activity blocks it. The default implementation always returns true.

See Also

· SearchManager

public boolean onTouchEvent (MotionEvent event)

Since: API Level 1

Called when a touch screen event was not handled by any of the views under it. This is most useful to process touch events that happen outside of your window bounds, where there is no view to receive it.

Parameters

event

The touch screen event being processed.

Returns

· Return true if you have consumed the event, false if you haven't. The default implementation always returns false.

public boolean onTrackballEvent (MotionEvent event)

Since: API Level 1

Called when the trackball was moved and not handled by any of the views inside of the activity. So, for example, if the trackball moves while focus is on a button, you will receive a call here because buttons do not normally do anything with trackball events. The call here happens before trackball movements are converted to DPAD key events, which then get sent back to the view hierarchy, and will be processed at the point for things like focus navigation.

Trackball有所动作并没有被当前activity的任何view所处理,将调用此方法。

Parameters

event

The trackball event being processed.

Returns

· Return true if you have consumed the event, false if you haven't. The default implementation always returns false.

public void onUserInteraction ()

Since: API Level 3

Called whenever a key, touch, or trackball event is dispatched to the activity. Implement this method if you wish to know that the user has interacted with the device in some way while your activity is running. This callback and onUserLeaveHint() are intended to help activities manage status bar notifications intelligently; specifically, for helping activities determine the proper time to cancel a notfication.

All calls to your activity's onUserLeaveHint() callback will be accompanied by calls to onUserInteraction(). This ensures that your activity will be told of relevant user activity such as pulling down the notification pane and touching an item there.

Note that this callback will be invoked for the touch down action that begins a touch gesture, but may not be invoked for the touch-moved and touch-up actions that follow.

See Also

· onUserLeaveHint()

public void onWindowAttributesChanged (WindowManager.LayoutParams params)

Since: API Level 1

This is called whenever the current window attributes change.

public void onWindowFocusChanged (boolean hasFocus)

Since: API Level 1

Called when the current Window of the activity gains or loses focus. This is the best indicator of whether this activity is visible to the user. The default implementation clears the key tracking state, so should always be called.

当前activity用户的window失去焦点时被调用,这个是用于标示activity是否可见的最好办法。

Note that this provides information about global focus state, which is managed independently of activity lifecycles. As such, while focus changes will generally have some relation to lifecycle changes (an activity that is stopped will not generally get window focus), you should not rely on any particular order between the callbacks here and those in the other lifecycle methods such as onResume().

As a general rule, however, a resumed activity will have window focus... unless it has displayed other dialogs or popups that take input focus, in which case the activity itself will not have focus when the other windows have it. Likewise, the system may display system-level windows (such as the status bar notification panel or a system alert) which will temporarily take window input focus without pausing the foreground activity.

Parameters

hasFocus

Whether the window of this activity has focus.

See Also

· hasWindowFocus()

· onResume()

· onWindowFocusChanged(boolean)

public void openContextMenu (View view)

Since: API Level 1

Programmatically opens the context menu for a particular view. The view should have been added via registerForContextMenu(View).

代码控制打开ContextMenu.

Parameters

view

The view to show the context menu for.

public void openOptionsMenu ()

Since: API Level 1

Programmatically opens the options menu. If the options menu is already open, this method does nothing.

代码控制打开opitionMenu

public void overridePendingTransition (int enterAnim, int exitAnim)

Since: API Level 5

Call immediately after one of the flavors of startActivity(Intent) or finish() to specify an explicit transition animation to perform next.

用于切换activity时的动画。

Parameters

enterAnim

A resource ID of the animation resource to use for the incoming activity. Use 0 for no animation.

exitAnim

A resource ID of the animation resource to use for the outgoing activity. Use 0 for no animation.

public void registerForContextMenu (View view)

Since: API Level 1

Registers a context menu to be shown for the given view (multiple views can show the context menu). This method will set the View.OnCreateContextMenuListener on the view to this activity, so onCreateContextMenu(ContextMenu, View, ContextMenuInfo) will be called when it is time to show the context menu.

设置ContextMenu,因为Activity实现了onCreateContextMenuListener,所以实际上是调用的view.setonCreateContextMenuListener(this).

Parameters

view

The view that should show a context menu.

See Also

· unregisterForContextMenu(View)

public final void removeDialog (int id)

Since: API Level 1

Removes any internal references to a dialog managed by this Activity. If the dialog is showing, it will dismiss it as part of the clean up. This can be useful if you know that you will never show a dialog again and want to avoid the overhead of saving and restoring it in the future.

Parameters

id

The id of the managed dialog.

See Also

· onCreateDialog(int)

· onPrepareDialog(int, Dialog)

· showDialog(int)

· dismissDialog(int)

public final boolean requestWindowFeature (int featureId)

Since: API Level 1

Enable extended window features. This is a convenience for calling getWindow().requestFeature().

Parameters

featureId

The desired feature as defined in Window.

Returns

· Returns true if the requested feature is supported and now enabled.

See Also

· requestFeature(int)

public final void runOnUiThread (Runnable action)

Since: API Level 1

Runs the specified action on the UI thread. If the current thread is the UI thread, then the action is executed immediately. If the current thread is not the UI thread, the action is posted to the event queue of the UI thread.

设置runnable对象在UI线程中执行,如果当前线程是UI线程,将理解执行,如果非UI线程,那么将发送到UI线程的消息队列。

源码如下所示:

public final void runOnUiThread(Runnable action) {

if (Thread.currentThread() != mUiThread) {

mHandler.post(action);

} else {

action.run();

}

}

Parameters

action

the action to run on the UI thread

public void setContentView (int layoutResID)

Since: API Level 1

Set the activity content from a layout resource. The resource will be inflated, adding all top-level views to the activity.

Parameters

layoutResID

Resource ID to be inflated.

public void setContentView (View view, ViewGroup.LayoutParams params)

Since: API Level 1

Set the activity content to an explicit view. This view is placed directly into the activity's view hierarchy. It can itself be a complex view hierarhcy.

Parameters

view

The desired content to display.

params

Layout parameters for the view.

public void setContentView (View view)

Since: API Level 1

Set the activity content to an explicit view. This view is placed directly into the activity's view hierarchy. It can itself be a complex view hierarhcy.

设置包含view的几个重载函数,需要注意其区别。

Parameters

view

The desired content to display.

public final void setDefaultKeyMode (int mode)

Since: API Level 1

Select the default key handling for this activity. This controls what will happen to key events that are not otherwise handled. The default mode (DEFAULT_KEYS_DISABLE) will simply drop them on the floor. Other modes allow you to launch the dialer (DEFAULT_KEYS_DIALER), execute a shortcut in your options menu without requiring the menu key be held down (DEFAULT_KEYS_SHORTCUT), or launch a search (DEFAULT_KEYS_SEARCH_LOCAL and DEFAULT_KEYS_SEARCH_GLOBAL).

Note that the mode selected here does not impact the default handling of system keys, such as the "back" and "menu" keys, and your activity and its views always get a first chance to receive and handle all application keys.

设置快捷键。默认情况下是设置的DEFAULT_KEYS_DISABLE,其他模式允许用户快捷的执行option menu或者加载search.

这里的设置并不影响系统默认的快捷处理,比如说backmenu按键。Activity总是有限处理系统的快捷方式。

Parameters

mode

The desired default key mode constant.

See Also

· DEFAULT_KEYS_DISABLE

· DEFAULT_KEYS_DIALER

· DEFAULT_KEYS_SHORTCUT

· DEFAULT_KEYS_SEARCH_LOCAL

· DEFAULT_KEYS_SEARCH_GLOBAL

· onKeyDown(int, KeyEvent)

public final void setFeatureDrawable (int featureId, Drawable drawable)

Since: API Level 1

Convenience for calling setFeatureDrawable(int, Drawable).

public final void setFeatureDrawableAlpha (int featureId, int alpha)

Since: API Level 1

Convenience for calling setFeatureDrawableAlpha(int, int).

public final void setFeatureDrawableResource (int featureId, int resId)

Since: API Level 1

Convenience for calling setFeatureDrawableResource(int, int).

public final void setFeatureDrawableUri (int featureId, Uri uri)

Since: API Level 1

Convenience for calling setFeatureDrawableUri(int, Uri).

以上几个setFeatureXXX方式都是利用activity包装调用了Window的相应函数。

public void setIntent (Intent newIntent)

Since: API Level 1

Change the intent returned by getIntent(). This holds a reference to the given intent; it does not copy it. Often used in conjunction with onNewIntent(Intent).

Parameters

newIntent

The new Intent object to return from getIntent

See Also

· getIntent()

· onNewIntent(Intent)

public void setPersistent (boolean isPersistent)

Since: API Level 1

Control whether this activity is required to be persistent. By default activities are not persistent; setting this to true will prevent the system from stopping this activity or its process when running low on resources.

设置activity是否长久有效,默认是不保持的。如果设置了这个标志,可以防止系统在低内存下kill或者stop这个activity或者他的process

You should avoid using this method, it has severe negative consequences on how well the system can manage its resources. A better approach is to implement an application service that you control with startService(Intent) and stopService(Intent).

尽量避免使用这个方法,因为对server如何管理资源有负面影响。更好的解决办法是实现一个server 并通过startServerstopServer来控制。

Parameters

isPersistent

Control whether the current activity must be persistent, true if so, false for the normal behavior.

public final void setProgress (int progress)

Since: API Level 1

Sets the progress for the progress bars in the title.

设置title的进度条

In order for the progress bar to be shown, the feature must be requested via requestWindowFeature(int).

Parameters

progress

The progress for the progress bar. Valid ranges are from 0 to 10000 (both inclusive). If 10000 is given, the progress bar will be completely filled and will fade out.

public final void setProgressBarIndeterminate (boolean indeterminate)

Since: API Level 1

Sets whether the horizontal progress bar in the title should be indeterminate (the circular is always indeterminate).

In order for the progress bar to be shown, the feature must be requested via requestWindowFeature(int).

Parameters

indeterminate

Whether the horizontal progress bar should be indeterminate.

public final void setProgressBarIndeterminateVisibility (boolean visible)

Since: API Level 1

Sets the visibility of the indeterminate progress bar in the title.

设置窗口的属性(下同)

In order for the progress bar to be shown, the feature must be requested via requestWindowFeature(int).

Parameters

visible

Whether to show the progress bars in the title.

public final void setProgressBarVisibility (boolean visible)

Since: API Level 1

Sets the visibility of the progress bar in the title.

In order for the progress bar to be shown, the feature must be requested via requestWindowFeature(int).

Parameters

visible

Whether to show the progress bars in the title.

public void setRequestedOrientation (int requestedOrientation)

Since: API Level 1

Change the desired orientation of this activity. If the activity is currently in the foreground or otherwise impacting the screen orientation, the screen will immediately be changed (possibly causing the activity to be restarted). Otherwise, this will be used the next time the activity is visible.

设置期望的屏幕方向。如果activity是顶部的或者其他影响屏幕方向的acitivity,屏幕会立即改变。 否则会在activity下次可见时生效。

Parameters

requestedOrientation

An orientation constant as used in ActivityInfo.screenOrientation.

public final void setResult (int resultCode, Intent data)

Since: API Level 1

Call this to set the result that your activity will return to its caller.

Parameters

resultCode

The result code to propagate back to the originating activity, often RESULT_CANCELED or RESULT_OK

data

The data to propagate back to the originating activity.

See Also

· RESULT_CANCELED

· RESULT_OK

· RESULT_FIRST_USER

· setResult(int)

public final void setResult (int resultCode)

Since: API Level 1

Call this to set the result that your activity will return to its caller.

Parameters

resultCode

The result code to propagate back to the originating activity, often RESULT_CANCELED or RESULT_OK

See Also

· RESULT_CANCELED

· RESULT_OK

· RESULT_FIRST_USER

· setResult(int, Intent)

public final void setSecondaryProgress (int secondaryProgress)

Since: API Level 1

Sets the secondary progress for the progress bar in the title. This progress is drawn between the primary progress (set via setProgress(int) and the background. It can be ideal for media scenarios such as showing the buffering progress while the default progress shows the play progress.

In order for the progress bar to be shown, the feature must be requested via requestWindowFeature(int).

Parameters

secondaryProgress

The secondary progress for the progress bar. Valid ranges are from 0 to 10000 (both inclusive).

public void setTitle (int titleId)

Since: API Level 1

Change the title associated with this activity. If this is a top-level activity, the title for its window will change. If it is an embedded activity, the parent can do whatever it wants with it.

public void setTitle (CharSequence title)

Since: API Level 1

Change the title associated with this activity. If this is a top-level activity, the title for its window will change. If it is an embedded activity, the parent can do whatever it wants with it.

public void setTitleColor (int textColor)

Since: API Level 1

public void setVisible (boolean visible)

Since: API Level 3

Control whether this activity's main window is visible. This is intended only for the special case of an activity that is not going to show a UI itself, but can't just finish prior to onResume() because it needs to wait for a service binding or such. Setting this to false allows you to prevent your UI from being shown during that time.

The default value for this is taken from the windowNoDisplay attribute of the activity's theme.

public final void setVolumeControlStream (int streamType)

Since: API Level 1

Suggests an audio stream whose volume should be changed by the hardware volume controls.

The suggested audio stream will be tied to the window of this Activity. If the Activity is switched, the stream set here is no longer the suggested stream. The client does not need to save and restore the old suggested stream value in onPause and onResume.

Parameters

streamType

The type of the audio stream whose volume should be changed by the hardware volume controls. It is not guaranteed that the hardware volume controls will always change this stream's volume (for example, if a call is in progress, its stream's volume may be changed instead). To reset back to the default, use USE_DEFAULT_STREAM_TYPE.

public final void showDialog (int id)

Since: API Level 1

Show a dialog managed by this activity. A call to onCreateDialog(int) will be made with the same id the first time this is called for a given id. From thereafter, the dialog will be automatically saved and restored. Each time a dialog is shown, onPrepareDialog(int, Dialog) will be made to provide an opportunity to do any timely preparation.

显示一个被当前activity管理的dialog. 在第一次调用此函数时会调用onCreateDialog以相同的id. 每次显示dialog时,都可以通过onPrepareDialog来改变其显示。

Parameters

id

The id of the managed dialog.

See Also

· Dialog

· onCreateDialog(int)

· onPrepareDialog(int, Dialog)

· dismissDialog(int)

· removeDialog(int)

public void startActivity (Intent intent)

Since: API Level 1

Launch a new activity. You will not receive any information about when the activity exits. This implementation overrides the base version, providing information about the activity performing the launch. Because of this additional information, the FLAG_ACTIVITY_NEW_TASK launch flag is not required; if not specified, the new activity will be added to the task of the caller.

startActivity其实还是调用的startActivityForResult.只是requestCode == -1.

This method throws ActivityNotFoundException if there was no Activity found to run the given Intent.

Parameters

intent

The intent to start.

Throws

android.content.ActivityNotFoundException

See Also

· startActivityForResult(Intent, int)

public void startActivityForResult (Intent intent, int requestCode)

Since: API Level 1

Launch an activity for which you would like a result when it finished. When this activity exits, your onActivityResult() method will be called with the given requestCode. Using a negative requestCode is the same as calling startActivity(Intent) (the activity is not launched as a sub-activity).

Note that this method should only be used with Intent protocols that are defined to return a result. In other protocols (such as ACTION_MAIN or ACTION_VIEW), you may not get the result when you expect. For example, if the activity you are launching uses the singleTask launch mode, it will not run in your task and thus you will immediately receive a cancel result.

这个方法只能用于支持返回结果的Intent 协议。在其他的Intent定义类型中(比如ACTION_MAINACTION_VIEW),并不能入期望的那样获得结果。例如当加载的activity以单线程启动模式加载,那么并不运行在启动这个activity的线程中,所以会立即返回一个cancel结果。

As a special case, if you call startActivityForResult() with a requestCode >= 0 during the initial onCreate(Bundle savedInstanceState)/onResume() of your activity, then your window will not be displayed until a result is returned back from the started activity. This is to avoid visible flickering when redirecting to another activity.

当在onCrateonResume中初始化activity时,如果用requestCode >= 0 来调用startActivityForResult,当前的窗口会等到结果返回后才能显示,这样是为了避免activity切换带来的闪烁。

以下是源代码,可以更好理解上面的阐述。

public void startActivityForResult(Intent intent, int requestCode) {

if (mParent == null) {

Instrumentation.ActivityResult ar =

mInstrumentation.execStartActivity(

this, mMainThread.getApplicationThread(), mToken, this,

intent, requestCode);

if (ar != null) {

mMainThread.sendActivityResult(

mToken, mEmbeddedID, requestCode, ar.getResultCode(),

ar.getResultData());

}

if (requestCode >= 0) {

// If this start is requesting a result, we can avoid making

// the activity visible until the result is received. Setting

// this code during onCreate(Bundle savedInstanceState) or onResume() will keep the

// activity hidden during this time, to avoid flickering.

// This can only be done when a result is requested because

// that guarantees we will get information back when the

// activity is finished, no matter what happens to it.

mStartedActivity = true;

}

} else {

mParent.startActivityFromChild(this, intent, requestCode);

}

}

This method throws ActivityNotFoundException if there was no Activity found to run the given Intent.

Parameters

intent

The intent to start.

requestCode

If >= 0, this code will be returned in onActivityResult() when the activity exits.

Throws

android.content.ActivityNotFoundException

See Also

· startActivity(Intent)

public void startActivityFromChild (Activity child, Intent intent, int requestCode)

Since: API Level 1

This is called when a child activity of this one calls its startActivity(Intent) or startActivityForResult(Intent, int) method.

This method throws ActivityNotFoundException if there was no Activity found to run the given Intent.

Parameters

child

The activity making the call.

intent

The intent to start.

requestCode

Reply request code. < 0 if reply is not requested.

Throws

android.content.ActivityNotFoundException

See Also

· startActivity(Intent)

· startActivityForResult(Intent, int)

public boolean startActivityIfNeeded (Intent intent, int requestCode)

Since: API Level 1

A special variation to launch an activity only if a new activity instance is needed to handle the given Intent. In other words, this is just like startActivityForResult(Intent, int) except: if you are using the FLAG_ACTIVITY_SINGLE_TOP flag, or singleTask or singleTop launchMode, and the activity that handles intent is the same as your currently running activity, then a new instance is not needed. In this case, instead of the normal behavior of calling onNewIntent(Intent) this function will return and you can handle the Intent yourself.

This function can only be called from a top-level activity; if it is called from a child activity, a runtime exception will be thrown.

只能被顶部acitivity调用,否则会有异常。

Parameters

intent

The intent to start.

requestCode

If >= 0, this code will be returned in onActivityResult() when the activity exits, as described in startActivityForResult(Intent, int).

Returns

· If a new activity was launched then true is returned; otherwise false is returned and you must handle the Intent yourself.

See Also

· startActivity(Intent)

· startActivityForResult(Intent, int)

public void startIntentSender (IntentSender intent, Intent fillInIntent, int flagsMask, int flagsValues, int extraFlags)

Since: API Level 5

Like startActivity(Intent), but taking a IntentSender to start; see startIntentSenderForResult(IntentSender, int, Intent, int, int, int) for more information.

Parameters

intent

The IntentSender to launch.

fillInIntent

If non-null, this will be provided as the intent parameter to sendIntent(Context, int, Intent, IntentSender.OnFinished, Handler).

flagsMask

Intent flags in the original IntentSender that you would like to change.

flagsValues

Desired values for any bits set in flagsMask

extraFlags

Always set to 0.

Throws

IntentSender.SendIntentException

public void startIntentSenderForResult (IntentSender intent, int requestCode, Intent fillInIntent, int flagsMask, int flagsValues, int extraFlags)

Since: API Level 5

Like startActivityForResult(Intent, int), but allowing you to use a IntentSender to describe the activity to be started. If the IntentSender is for an activity, that activity will be started as if you had called the regular startActivityForResult(Intent, int) here; otherwise, its associated action will be executed (such as sending a broadcast) as if you had called IntentSender.sendIntent on it.

Parameters

intent

The IntentSender to launch.

requestCode

If >= 0, this code will be returned in onActivityResult() when the activity exits.

fillInIntent

If non-null, this will be provided as the intent parameter to sendIntent(Context, int, Intent, IntentSender.OnFinished, Handler).

flagsMask

Intent flags in the original IntentSender that you would like to change.

flagsValues

Desired values for any bits set in flagsMask

extraFlags

Always set to 0.

Throws

IntentSender.SendIntentException

public void startIntentSenderFromChild (Activity child, IntentSender intent, int requestCode, Intent fillInIntent, int flagsMask, int flagsValues, int extraFlags)

Since: API Level 5

Like startActivityFromChild(Activity, Intent, int), but taking a IntentSender; see startIntentSenderForResult(IntentSender, int, Intent, int, int, int) for more information.

Throws

IntentSender.SendIntentException

public void startManagingCursor (Cursor c)

Since: API Level 1

This method allows the activity to take care of managing the given Cursor's lifecycle for you based on the activity's lifecycle. That is, when the activity is stopped it will automatically call deactivate() on the given Cursor, and when it is later restarted it will call requery() for you. When the activity is destroyed, all managed Cursors will be closed automatically.

Parameters

c

The Cursor to be managed.

See Also

· managedQuery(android.net.Uri, String[], String, String[], String)

· stopManagingCursor(Cursor)

public boolean startNextMatchingActivity (Intent intent)

Since: API Level 1

Special version of starting an activity, for use when you are replacing other activity components. You can use this to hand the Intent off to the next Activity that can handle it. You typically call this in onCreate(Bundle) with the Intent returned by getIntent().

以给定的Inteng启动可以处理当前Intengactivity(一般是让系统来自动选择)

Parameters

intent

The intent to dispatch to the next activity. For correct behavior, this must be the same as the Intent that started your own activity; the only changes you can make are to the extras inside of it.

Returns

· Returns a boolean indicating whether there was another Activity to start: true if there was a next activity to start, false if there wasn't. In general, if true is returned you will then want to call finish() on yourself.

public void startSearch (String initialQuery, boolean selectInitialQuery, Bundle appSearchData, boolean globalSearch)

Since: API Level 1

This hook is called to launch the search UI.

调用系统的search UI.

It is typically called from onSearchRequested(), either directly from Activity.onSearchRequested() or from an overridden version in any given Activity. If your goal is simply to activate search, it is preferred to call onSearchRequested(), which may have been overriden elsewhere in your Activity. If your goal is to inject specific data such as context data, it is preferred to override onSearchRequested(), so that any callers to it will benefit from the override.

Parameters

initialQuery

Any non-null non-empty string will be inserted as pre-entered text in the search query box.

selectInitialQuery

If true, the intial query will be preselected, which means that any further typing will replace it. This is useful for cases where an entire pre-formed query is being inserted. If false, the selection point will be placed at the end of the inserted query. This is useful when the inserted query is text that the user entered, and the user would expect to be able to keep typing. This parameter is only meaningful if initialQuery is a non-empty string.

appSearchData

An application can insert application-specific context here, in order to improve quality or specificity of its own searches. This data will be returned with SEARCH intent(s). Null if no extra data is required.

globalSearch

If false, this will only launch the search that has been specifically defined by the application (which is usually defined as a local search). If no default search is defined in the current application or activity, global search will be launched. If true, this will always launch a platform-global (e.g. web-based) search instead.

See Also

· SearchManager

· onSearchRequested()

public void stopManagingCursor (Cursor c)

Since: API Level 1

Given a Cursor that was previously given to startManagingCursor(Cursor), stop the activity's management of that cursor.

接触当前Activitycursor之间的绑定关系,这样cursor有所变化时 不会再自动刷新

Parameters

c

The Cursor that was being managed.

See Also

· startManagingCursor(Cursor)

public void takeKeyEvents (boolean get)

Since: API Level 1

Request that key events come to this activity. Use this if your activity has no views with focus, but the activity still wants a chance to process key events.

通过这个函数设置当activity并没有存在焦点时, 也让系统传递按键事件。

See Also

· takeKeyEvents(boolean)

public void triggerSearch (String query, Bundle appSearchData)

Since: API Level 5

Similar to startSearch(String, boolean, Bundle, boolean), but actually fires off the search query after invoking the search dialog. Made available for testing purposes.

Parameters

query

The query to trigger. If empty, the request will be ignored.

appSearchData

An application can insert application-specific context here, in order to improve quality or specificity of its own searches. This data will be returned with SEARCH intent(s). Null if no extra data is required.

public void unregisterForContextMenu (View view)

Since: API Level 1

Prevents a context menu to be shown for the given view. This method will remove the View.OnCreateContextMenuListener on the view.

反注册ContextMenu

Parameters

view

The view that should stop showing a context menu.

See Also

· registerForContextMenu(View)

Protected Methods

protected void finalize ()

Since: API Level 1

Is called before the object's memory is being reclaimed by the VM. This can only happen once the VM has detected, during a run of the garbage collector, that the object is no longer reachable by any thread of the running application.

在系统回收当前对象内存时调用,仅仅在VM监测到当前对象不会被其他运行线程再调用时调用。

The method can be used to free system resources or perform other cleanup before the object is garbage collected. The default implementation of the method is empty, which is also expected by the VM, but subclasses can override finalize() as required. Uncaught exceptions which are thrown during the execution of this method cause it to terminate immediately but are otherwise ignored.

Note that the VM does guarantee that finalize() is called at most once for any object, but it doesn't guarantee when (if at all) finalize() will be called. For example, object B's finalize() can delay the execution of object A's finalize() method and therefore it can delay the reclamation of A's memory. To be safe, use a ReferenceQueue, because it provides more control over the way the VM deals with references during garbage collection.

VM 能够保证在每个对象最多执行一次finalize(),但是并不能保证finalize()什么时候被执行(如果真会的执行的话)。例如,B对象的finalize()可能延迟A对象的finalize()的执行,因而延迟了A的内存的回收

Throws

Throwable

protected void onActivityResult (int requestCode, int resultCode, Intent data)

Since: API Level 1

Called when an activity you launched exits, giving you the requestCode you started it with, the resultCode it returned, and any additional data from it. The resultCode will be RESULT_CANCELED if the activity explicitly returned that, didn't return any result, or crashed during its operation.

activity启动的sub Activity退出时,onActivityResule会通过传递启动是的requestCoderesultcode 加上额外的数据来调用这个函数。

You will receive this call immediately before onResume() when your activity is re-starting.

会在onResume之前接受到这个回调。

Parameters

requestCode

The integer request code originally supplied to startActivityForResult(), allowing you to identify who this result came from.

resultCode

The integer result code returned by the child activity through its setResult().

data

An Intent, which can return result data to the caller (various data can be attached to Intent "extras").

See Also

· startActivityForResult(Intent, int)

· createPendingResult(int, Intent, int)

· setResult(int)

protected void onApplyThemeResource (Resources.Theme theme, int resid, boolean first)

Since: API Level 1

Called by setTheme(int) and getTheme() to apply a theme resource to the current Theme object. Can override to change the default (simple) behavior. This method will not be called in multiple threads simultaneously.

Parameters

theme

The Theme object being modified.

resid

The theme style resource being applied to theme.

first

Set to true if this is the first time a style is being applied to theme.

protected void onChildTitleChanged (Activity childActivity, CharSequence title)

Since: API Level 1

protected void onCreate (Bundle savedInstanceState)

Since: API Level 1

Called when the activity is starting. This is where most initialization should go: calling setContentView(int) to inflate the activity's UI, using findViewById(int) to programmatically interact with widgets in the UI, calling managedQuery(android.net.Uri, String[], String, String[], String) to retrieve cursors for data being displayed, etc.

You can call finish() from within this function, in which case onDestroy() will be immediately called without any of the rest of the activity lifecycle (onStart(), onResume(), onPause(), etc) executing.

在此方法中直接调用finish(),则会直接调用onDestory,而绕过原来生命周期中的onStart,onResume,onPause等回调。

Derived classes must call through to the super class's implementation of this method. If they do not, an exception will be thrown.

Parameters

savedInstanceState

If the activity is being re-initialized after previously being shut down then this Bundle contains the data it most recently supplied in onSaveInstanceState(Bundle). Note: Otherwise it is null.

See Also

· onStart()

· onSaveInstanceState(Bundle)

· onRestoreInstanceState(Bundle)

· onPostCreate(Bundle)

protected Dialog onCreateDialog (int id)

Since: API Level 1

Callback for creating dialogs that are managed (saved and restored) for you by the activity. If you use showDialog(int), the activity will call through to this method the first time, and hang onto it thereafter. Any dialog that is created by this method will automatically be saved and restored for you, including whether it is showing. If you would like the activity to manage the saving and restoring dialogs for you, you should override this method and handle any ids that are passed to showDialog(int). If you would like an opportunity to prepare your dialog before it is shown, override onPrepareDialog(int, Dialog).

此回调用于被当前Activity管理的dialog的创建,如果调用showDialog,系统会在第一次时调用此方法,这个方法创建的dialog会自动的被保存其状态,无论是否正在显示。如果想管理dialog,那么需要重载这个方法。如果想在dialog显示之前选择性的设置dialog,需要重载onPrepareDialog(int, Dialog).

Parameters

id

The id of the dialog.

Returns

· The dialog

See Also

· onPrepareDialog(int, Dialog)

· showDialog(int)

· dismissDialog(int)

· removeDialog(int)

protected void onDestroy ()

Since: API Level 1

Perform any final cleanup before an activity is destroyed. This can happen either because the activity is finishing (someone called finish() on it, or because the system is temporarily destroying this instance of the activity to save space. You can distinguish between these two scenarios with the isFinishing() method.

Note: do not count on this method being called as a place for saving data! For example, if an activity is editing data in a content provider, those edits should be committed in either onPause() or onSaveInstanceState(Bundle), not here. This method is usually implemented to free resources like threads that are associated with an activity, so that a destroyed activity does not leave such things around while the rest of its application is still running. There are situations where the system will simply kill the activity's hosting process without calling this method (or any others) in it, so it should not be used to do things that are intended to remain around after the process goes away.

不要在此处保存用户状态,而仅仅用于释放资源

Derived classes must call through to the super class's implementation of this method. If they do not, an exception will be thrown.

See Also

· onPause()

· onStop()

· finish()

· isFinishing()

protected void onNewIntent (Intent intent)

Since: API Level 1

This is called for activities that set launchMode to "singleTop" in their package, or if a client used the FLAG_ACTIVITY_SINGLE_TOP flag when calling startActivity(Intent). In either case, when the activity is re-launched while at the top of the activity stack instead of a new instance of the activity being started, onNewIntent() will be called on the existing instance with the Intent that was used to re-launch it.

Activity的启动模式设置为singleTop或客户端在调用activity时设置了FLAG_ACTIVITY_SINGLE_TOP,则此回调会被调用。

无论哪种情况,activity都将在重新加载后至于activity stack的顶部而不是新的activity实例重新开始。 OnNewIntent在已经有存在的拥有intent的实例在重新加载时被调用。

An activity will always be paused before receiving a new intent, so you can count on onResume() being called after this method.

Activity总是在接受新的intent之前处于paused状态。所以此方法后onResume总是被调用到。

Note that getIntent() still returns the original Intent. You can use setIntent(Intent) to update it to this new Intent.

getIntent总是获取原来的Intent,可以通过setIntent来取代原有的Intent

Parameters

intent

The new intent that was started for the activity.

See Also

· getIntent()

· setIntent(Intent)

· onResume()

protected void onPause ()

Since: API Level 1

Called as part of the activity lifecycle when an activity is going into the background, but has not (yet) been killed. The counterpart to onResume().

When activity B is launched in front of activity A, this callback will be invoked on A. B will not be created until A's onPause() returns, so be sure to not do anything lengthy here.

B切换到A的前面时,知道AonPause返回后B才能创建成功。

This callback is mostly used for saving any persistent state the activity is editing, to present a "edit in place" model to the user and making sure nothing is lost if there are not enough resources to start the new activity without first killing this one. This is also a good place to do things like stop animations and other things that consume a noticeable mount of CPU in order to make the switch to the next activity as fast as possible, or to close resources that are exclusive access such as the camera.

这里可以用于停止动画等其他时间以便更快的切换到下一个activity.

In situations where the system needs more memory it may kill paused processes to reclaim resources. Because of this, you should be sure that all of your state is saved by the time you return from this function. In general onSaveInstanceState(Bundle) is used to save per-instance state in the activity and this method is used to store global persistent data (in content providers, files, etc.)

After receiving this call you will usually receive a following call to onStop() (after the next activity has been resumed and displayed), however in some cases there will be a direct call back to onResume() without going through the stopped state.

Derived classes must call through to the super class's implementation of this method. If they do not, an exception will be thrown.

See Also

· onResume()

· onSaveInstanceState(Bundle)

· onStop()

protected void onPostCreate (Bundle savedInstanceState)

Since: API Level 1

Called when activity start-up is complete (after onStart() and onRestoreInstanceState(Bundle) have been called). Applications will generally not implement this method; it is intended for system classes to do final initialization after application code has run.

同下(PS,因为本人是从最后开始往上写的,所以 ……呵呵)

Derived classes must call through to the super class's implementation of this method. If they do not, an exception will be thrown.

Parameters

savedInstanceState

If the activity is being re-initialized after previously being shut down then this Bundle contains the data it most recently supplied in onSaveInstanceState(Bundle). Note: Otherwise it is null.

See Also

· onCreate(Bundle)

protected void onPostResume ()

Since: API Level 1

Called when activity resume is complete (after onResume() has been called). Applications will generally not implement this method; it is intended for system classes to do final setup after application resume code has run.

应用程序一般不需要实现此方法,一般用于系统函数在完成resume后做最后的加载。

Derived classes must call through to the super class's implementation of this method. If they do not, an exception will be thrown.

See Also

· onResume()

protected void onPrepareDialog (int id, Dialog dialog)

Since: API Level 1

Provides an opportunity to prepare a managed dialog before it is being shown.

Override this if you need to update a managed dialog based on the state of the application each time it is shown. For example, a time picker dialog might want to be updated with the current time. You should call through to the superclass's implementation. The default implementation will set this Activity as the owner activity on the Dialog.

在这个回调中,可以更新dialog的状态。如果有此需要,可以重载这个函数。

Parameters

id

The id of the managed dialog.

dialog

The dialog.

See Also

· onCreateDialog(int)

· showDialog(int)

· dismissDialog(int)

· removeDialog(int)

protected void onRestart ()

Since: API Level 1

Called after onStop() when the current activity is being re-displayed to the user (the user has navigated back to it). It will be followed by onStart() and then onResume().

For activities that are using raw Cursor objects (instead of creating them through managedQuery(android.net.Uri, String[], String, String[], String), this is usually the place where the cursor should be requeried (because you had deactivated it in onStop().

在这里最好调用当前activity管理的cursorrequey以便更新数据。

Derived classes must call through to the super class's implementation of this method. If they do not, an exception will be thrown.

See Also

· onStop()

· onStart()

· onResume()

protected void onRestoreInstanceState (Bundle savedInstanceState)

Since: API Level 1

This method is called after onStart() when the activity is being re-initialized from a previously saved state, given here in state. Most implementations will simply use onCreate(Bundle) to restore their state, but it is sometimes convenient to do it here after all of the initialization has been done or to allow subclasses to decide whether to use your default implementation. The default implementation of this method performs a restore of any view state that had previously been frozen by onSaveInstanceState(Bundle).

activity从前一个状态初始化时在onStart之后调用。大多数时候是简单的用onCreate来恢复保存的状态,而有时候在这里允许子类是否调用默认构造函数(没看太明白,就当乱写吧)

This method is called between onStart() and onPostCreate(Bundle).

Parameters

savedInstanceState

the data most recently supplied in onSaveInstanceState(Bundle).

See Also

· onCreate(Bundle)

· onPostCreate(Bundle)

· onResume()

· onSaveInstanceState(Bundle)

protected void onResume ()

Since: API Level 1

Called after onRestoreInstanceState(Bundle), onRestart(), or onPause(), for your activity to start interacting with the user. This is a good place to begin animations, open exclusive-access devices (such as the camera), etc.

onRestoreInstanceState(Bundle), onRestart(), or onPause(),之后被调用,调用后就可以和用户进行交互了。这里可以用来放置动画,打开独享设备等。

Keep in mind that onResume is not the best indicator that your activity is visible to the user; a system window such as the keyguard may be in front. Use onWindowFocusChanged(boolean) to know for certain that your activity is visible to the user (for example, to resume a game).

OnResume并不是标示当前Activity可见的最好办法。 最好通过onwindowFocusChanged来确认说法可见。

Derived classes must call through to the super class's implementation of this method. If they do not, an exception will be thrown.

See Also

· onRestoreInstanceState(Bundle)

· onRestart()

· onPostResume()

· onPause()

protected void onSaveInstanceState (Bundle outState)

Since: API Level 1

Called to retrieve per-instance state from an activity before being killed so that the state can be restored in onCreate(Bundle) or onRestoreInstanceState(Bundle) (the Bundle populated by this method will be passed to both).

调用此方法去保存当前的activitykilled之前的状态,以便在onCreateonRestoreInstanceState的通过Bundle参数回复到原来的状态

This method is called before an activity may be killed so that when it comes back some time in the future it can restore its state. For example, if activity B is launched in front of activity A, and at some point activity A is killed to reclaim resources, activity A will have a chance to save the current state of its user interface via this method so that when the user returns to activity A, the state of the user interface can be restored via onCreate(Bundle) or onRestoreInstanceState(Bundle).

Do not confuse this method with activity lifecycle callbacks such as onPause(), which is always called when an activity is being placed in the background or on its way to destruction, or onStop() which is called before destruction. One example of when onPause() and onStop() is called and not this method is when a user navigates back from activity B to activity A: there is no need to call onSaveInstanceState(Bundle) on B because that particular instance will never be restored, so the system avoids calling it. An example when onPause() is called and not onSaveInstanceState(Bundle) is when activity B is launched in front of activity A: the system may avoid calling onSaveInstanceState(Bundle) on activity A if it isn't killed during the lifetime of B since the state of the user interface of A will stay intact.

activityonPause总是在被切换到后台时调用或者在其析构钱调用onStop,.一个例子就是当用户切换activity B切换到activity A,onPauseonStop被调用而此不会调用B的此方法,是因为当前实例永远不会restore,所以系统减少类似调用。

PS:这个说法要结合上面的两段整体理解)

The default implementation takes care of most of the UI per-instance state for you by calling onSaveInstanceState() on each view in the hierarchy that has an id, and by saving the id of the currently focused view (all of which is restored by the default implementation of onRestoreInstanceState(Bundle)). If you override this method to save additional information not captured by each individual view, you will likely want to call through to the default implementation, otherwise be prepared to save all of the state of each view yourself.

If called, this method will occur before onStop(). There are no guarantees about whether it will occur before or after onPause().

Parameters

outState

Bundle in which to place your saved state.

See Also

· onCreate(Bundle)

· onRestoreInstanceState(Bundle)

· onPause()

protected void onStart ()

Since: API Level 1

Called after onCreate(Bundle) — or after onRestart() when the activity had been stopped, but is now again being displayed to the user. It will be followed by onResume().

重新变为可见,在其后onResume被调用。

Derived classes must call through to the super class's implementation of this method. If they do not, an exception will be thrown.

这个就不用多说了,看看源码就知道了。

See Also

· onCreate(Bundle)

· onStop()

· onResume()

protected void onStop ()

Since: API Level 1

Called when you are no longer visible to the user. You will next receive either onRestart(), onDestroy(), or nothing, depending on later user activity.

Note that this method may never be called, in low memory situations where the system does not have enough memory to keep your activity's process running after its onPause() method is called.

activity变为不可见时被调用,根据用户的后续操作,可能会继续接受到onRestart,onDestory的调用。

activityonPause被调用后,在系统没有足够内存运行当前activity的进程时,可能这个方法再也不会被调用到。

Derived classes must call through to the super class's implementation of this method. If they do not, an exception will be thrown.

子类必须调用父类的onStop,否则将有异常抛出。

See Also

· onRestart()

· onResume()

· onSaveInstanceState(Bundle)

· onDestroy()

protected void onTitleChanged (CharSequence title, int color)

Since: API Level 1

protected void onUserLeaveHint ()

Since: API Level 3

Called as part of the activity lifecycle when an activity is about to go into the background as the result of user choice. For example, when the user presses the Home key, onUserLeaveHint() will be called, but when an incoming phone call causes the in-call Activity to be automatically brought to the foreground, onUserLeaveHint() will not be called on the activity being interrupted. In cases when it is invoked, this method is called right before the activity's onPause() callback.

This callback and onUserInteraction() are intended to help activities manage status bar notifications intelligently; specifically, for helping activities determine the proper time to cancel a notfication.

作为activity生命周期的一部分, onUserLeaveHint 在被用户即将切换到后台时会被调用到。例如,用户如果按了Home键,onUserLeaveHint将会被调用。但是当因有电话打进而引起in_call activity被切换到前台时,activity的中断并不会引起onUserLeaveHin的调用。当整个过程执行时,onUserLeaveHint正好在onPause之前调用。

OnUserLeaveHintonUserInteraction用于帮助管理activity的状态栏的通知。以便activity可以及时的更新notification的状态。

See Also

· onUserInteraction()

更多相关文章

  1. Android(安卓)LayoutInflater.inflate()方法的参数用途
  2. ListView/GridView 按住拖动黑线框/桌面背景透上来【已解决】
  3. startActivity调用流程及生命周期
  4. [原][Android]All WebView methods must be called on the same
  5. android下图片处理方法[转]
  6. Android(安卓)TTS学习——继续爱的表白
  7. ContentProvider原理分析二 MediaProvider publish .
  8. 【Android】NDK中log输出方法
  9. 【Android(安卓)开发教程】显示普通对话框

随机推荐

  1. 自己归纳 Android 四种布局简介
  2. React Native踩坑:集成到现有Android原生
  3. android主流分辨率
  4. Google正式推出Android 3.2开发工具
  5. 我的成长之路
  6. Android WatchDog分析
  7. android 怎样为多媒体文件生成缩略图
  8. android客户端向服务端传汉字乱码问题
  9. [转]Android虚拟电源管理驱动
  10. android 布局总结