An activity is a single, focused thing that the user can do. Almost all activities interact with the user, so the Activity class takes care of creating a window for you in which you can place your UI with setContentView(View). While activities are often presented to the user as full-screen windows, they can also be used in other ways: as floating windows (via a theme with windowIsFloating set) or embedded inside of another activity (using ActivityGroup). There are two methods almost all subclasses of Activity will implement:
To be of use with Context.startActivity(), all
activity classes must have a corresponding
<activity>
declaration in their package's AndroidManifest.xml
.
The Activity class is an important part of an application's overall lifecycle, and the way activities are launched and put together is a fundamental part of the platform's application model.
Topics covered here:
Activities in the system are managed as an activity stack. When a new activity is started, it is placed on the top of the stack and becomes the running activity -- the previous activity always remains below it in the stack, and will not come to the foreground again until the new activity exits.
An activity has essentially four states:
The following diagram shows the important state paths of an Activity. The square rectangles represent callback methods you can implement to perform operations when the Activity moves between states. The colored ovals are major states the Activity can be in.
There are three key loops you may be interested in monitoring within your activity:
The entire lifecycle of an activity is defined by the following Activity methods. All of these are hooks that you can override to do appropriate work when the activity changes state. All activities will implement onCreate(Bundle) to do their initial setup; many will also implement onPause() to commit changes to data and otherwise prepare to stop interacting with the user. You should always call up to your superclass when implementing these methods.
public class Activity extends ApplicationContext { protected void onCreate(Bundle savedInstanceState); protected void onStart(); protected void onRestart(); protected void onResume(); protected void onPause(); protected void onStop(); protected void onDestroy(); }
In general the movement through an activity's lifecycle looks like this:
Method | Description | Killable? | Next | ||
---|---|---|---|---|---|
onCreate() | Called when the activity is first created.
This is where you should do all of your normal static set up:
create views, bind data to lists, etc. This method also
provides you with a Bundle containing the activity's previously
frozen state, if there was one.
Always followed by |
No | onStart() |
||
onRestart() | Called after your activity has been stopped, prior to it being
started again.
Always followed by |
No | onStart() |
||
onStart() | Called when the activity is becoming visible to the user.
Followed by |
No | onResume() or onStop() |
||
onResume() | Called when the activity will start
interacting with the user. At this point your activity is at
the top of the activity stack, with user input going to it.
Always followed by |
No | onPause() |
||
onPause() | Called when the system is about to start resuming a previous
activity. This is typically used to commit unsaved changes to
persistent data, stop animations and other things that may be consuming
CPU, etc. Implementations of this method must be very quick because
the next activity will not be resumed until this method returns.
Followed by either |
Yes | onResume() oronStop() |
||
onStop() | Called when the activity is no longer visible to the user, because
another activity has been resumed and is covering this one. This
may happen either because a new activity is being started, an existing
one is being brought in front of this one, or this one is being
destroyed.
Followed by either |
Yes | onRestart() oronDestroy() |
||
onDestroy() | The final call you receive before your 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. | Yes | nothing |
Note the "Killable" column in the above table -- for those methods that are marked as being killable, after that method returns the process hosting the activity may killed by the system at any time without another line of its code being executed. Because of this, you should use the onPause() method to write any persistent data (such as user edits) to storage. In addition, the method onSaveInstanceState(Bundle) is called before placing the activity in such a background state, allowing you to save away any dynamic instance state in your activity into the given Bundle, to be later received in onCreate(Bundle) if the activity needs to be re-created. See the Process Lifecycle section for more information on how the lifecycle of a process is tied to the activities it is hosting. Note that it is important to save persistent data in onPause() instead of onSaveInstanceState(Bundle) because the later is not part of the lifecycle callbacks, so will not be called in every situation as described in its documentation.
For those methods that are not marked as being killable, the activity's
process will not be killed by the system starting from the time the method
is called and continuing after it returns. Thus an activity is in the killable
state, for example, between after onPause()
to the start of
onResume()
.
If the configuration of the device (as defined by the Resources.Configuration class) changes, then anything displaying a user interface will need to update to match that configuration. Because Activity is the primary mechanism for interacting with the user, it includes special support for handling configuration changes.
Unless you specify otherwise, a configuration change (such as a change in screen orientation, language, input devices, etc) will cause your current activity to be destroyed, going through the normal activity lifecycle process of onPause(), onStop(), and onDestroy() as appropriate. If the activity had been in the foreground or visible to the user, once onDestroy() is called in that instance then a new instance of the activity will be created, with whatever savedInstanceState the previous instance had generated from onSaveInstanceState(Bundle).
This is done because any application resource, including layout files, can change based on any configuration value. Thus the only safe way to handle a configuration change is to re-retrieve all resources, including layouts, drawables, and strings. Because activities must already know how to save their state and re-create themselves from that state, this is a convenient way to have an activity restart itself with a new configuration.
In some special cases, you may want to bypass restarting of your activity based on one or more types of configuration changes. This is done with the android:configChanges attribute in its manifest. For any types of configuration changes you say that you handle there, you will receive a call to your current activity's onConfigurationChanged(Configuration) method instead of being restarted. If a configuration change involves any that you do not handle, however, the activity will still be restarted and onConfigurationChanged(Configuration) will not be called.
The startActivity(Intent) method is used to start a new activity, which will be placed at the top of the activity stack. It takes a single argument, an Intent, which describes the activity to be executed.
Sometimes you want to get a result back from an activity when it ends. For example, you may start an activity that lets the user pick a person in a list of contacts; when it ends, it returns the person that was selected. To do this, you call the startActivityForResult(Intent, int) version with a second integer parameter identifying the call. The result will come back through your onActivityResult(int, int, Intent) method.
When an activity exits, it can call
setResult(int)
to return data back to its parent. It must always supply a result code,
which can be the standard results RESULT_CANCELED, RESULT_OK, or any
custom values starting at RESULT_FIRST_USER. In addition, it can optionally
return back an Intent containing any additional data it wants. All of this
information appears back on the
parent's Activity.onActivityResult()
, along with the integer
identifier it originally supplied.
If a child activity fails for any reason (such as crashing), the parent activity will receive a result with the code RESULT_CANCELED.
public class MyActivity extends Activity { ... static final int PICK_CONTACT_REQUEST = 0; protected boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER) { // When the user center presses, let them pick a contact. startActivityForResult( new Intent(Intent.ACTION_PICK, new Uri("content://contacts")), PICK_CONTACT_REQUEST); return true; } return false; } protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == PICK_CONTACT_REQUEST) { if (resultCode == RESULT_OK) { // A contact was picked. Here we will just display it // to the user. startActivity(new Intent(Intent.ACTION_VIEW, data)); } } } }
There are generally two kinds of persistent state than an activity will deal with: shared document-like data (typically stored in a SQLite database using a content provider) and internal state such as user preferences.
For content provider data, we suggest that activities use a "edit in place" user model. That is, any edits a user makes are effectively made immediately without requiring an additional confirmation step. Supporting this model is generally a simple matter of following two rules:
When creating a new document, the backing database entry or file for it is created immediately. For example, if the user chooses to write a new e-mail, a new entry for that e-mail is created as soon as they start entering data, so that if they go to any other activity after that point this e-mail will now appear in the list of drafts.
When an activity's onPause()
method is called, it should
commit to the backing content provider or file any changes the user
has made. This ensures that those changes will be seen by any other
activity that is about to run. You will probably want to commit
your data even more aggressively at key times during your
activity's lifecycle: for example before starting a new
activity, before finishing your own activity, when the user
switches between input fields, etc.
This model is designed to prevent data loss when a user is navigating between activities, and allows the system to safely kill an activity (because system resources are needed somewhere else) at any time after it has been paused. Note this implies that the user pressing BACK from your activity does not mean "cancel" -- it means to leave the activity with its current contents saved away. Cancelling edits in an activity must be provided through some other mechanism, such as an explicit "revert" or "undo" option.
See the content package for more information about content providers. These are a key aspect of how different activities invoke and propagate data between themselves.
The Activity class also provides an API for managing internal persistent state associated with an activity. This can be used, for example, to remember the user's preferred initial display in a calendar (day view or week view) or the user's default home page in a web browser.
Activity persistent state is managed with the method getPreferences(int), allowing you to retrieve and modify a set of name/value pairs associated with the activity. To use preferences that are shared across multiple application components (activities, receivers, services, providers), you can use the underlying Context.getSharedPreferences() method to retrieve a preferences object stored under a specific name. (Note that it is not possible to share settings data across application packages -- for that you will need a content provider.)
Here is an excerpt from a calendar activity that stores the user's preferred view mode in its persistent settings:
public class CalendarActivity extends Activity { ... static final int DAY_VIEW_MODE = 0; static final int WEEK_VIEW_MODE = 1; private SharedPreferences mPrefs; private int mCurViewMode; protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); SharedPreferences mPrefs = getSharedPreferences(); mCurViewMode = mPrefs.getInt("view_mode" DAY_VIEW_MODE); } protected void onPause() { super.onPause(); SharedPreferences.Editor ed = mPrefs.edit(); ed.putInt("view_mode", mCurViewMode); ed.commit(); } }
The ability to start a particular Activity can be enforced when it is declared in its manifest's <activity> tag. By doing so, other applications will need to declare a corresponding <uses-permission> element in their own manifest to be able to start that activity.
See the Security Model document for more information on permissions and security in general.
The Android system attempts to keep application process around for as long as possible, but eventually will need to remove old processes when memory runs low. As described in Activity Lifecycle, the decision about which process to remove is intimately tied to the state of the user's interaction with it. In general, there are four states a process can be in based on the activities running in it, listed here in order of importance. The system will kill less important processes (the last ones) before it resorts to killing more important processes (the first ones).
The foreground activity (the activity at the top of the screen that the user is currently interacting with) is considered the most important. Its process will only be killed as a last resort, if it uses more memory than is available on the device. Generally at this point the device has reached a memory paging state, so this is required in order to keep the user interface responsive.
A visible activity (an activity that is visible to the user but not in the foreground, such as one sitting behind a foreground dialog) is considered extremely important and will not be killed unless that is required to keep the foreground activity running.
A background activity (an activity that is not visible to the user and has been paused) is no longer critical, so the system may safely kill its process to reclaim memory for other foreground or visible processes. If its process needs to be killed, when the user navigates back to the activity (making it visible on the screen again), its onCreate(Bundle) method will be called with the savedInstanceState it had previously supplied in onSaveInstanceState(Bundle) so that it can restart itself in the same state as the user last left it.
An empty process is one hosting no activities or other application components (such as Service or BroadcastReceiver classes). These are killed very quickly by the system as memory becomes low. For this reason, any background operation you do outside of an activity must be executed in the context of an activity BroadcastReceiver or Service to ensure that the system knows it needs to keep your process around.
Sometimes an Activity may need to do a long-running operation that exists independently of the activity lifecycle itself. An example may be a camera application that allows you to upload a picture to a web site. The upload may take a long time, and the application should allow the user to leave the application will it is executing. To accomplish this, your Activity should start a Service in which the upload takes place. This allows the system to properly prioritize your process (considering it to be more important than other non-visible applications) for the duration of the upload, independent of whether the original activity is paused, stopped, or finished.
Value | ||||
---|---|---|---|---|
int | DEFAULT_KEYS_DIALER | Use with setDefaultKeyMode(int) to launch the dialer during default key handling. | 1 | 0x00000001 |
int | DEFAULT_KEYS_DISABLE | Use with setDefaultKeyMode(int) to turn off default handling of keys. | 0 | 0x00000000 |
int | DEFAULT_KEYS_SEARCH_GLOBAL | 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. |
4 | 0x00000004 |
int | DEFAULT_KEYS_SEARCH_LOCAL | Use with setDefaultKeyMode(int) to specify that unhandled keystrokes will start an application-defined search. | 3 | 0x00000003 |
int | DEFAULT_KEYS_SHORTCUT | Use with setDefaultKeyMode(int) to execute a menu shortcut in default key handling. | 2 | 0x00000002 |
int[] | FOCUSED_STATE_SET | |||
int | RESULT_CANCELED | Standard activity result: operation canceled. | 0 | 0x00000000 |
int | RESULT_FIRST_USER | Start of user-defined activity results. | 1 | 0x00000001 |
int | RESULT_OK | Standard activity result: operation succeeded. | -1 | 0xffffffff |
Activity() |
void | addContentView(View view, ViewGroup.LayoutParams params) | |||||
Add an additional content view to the activity. | ||||||
void | closeOptionsMenu() | |||||
Progammatically closes the options menu. | ||||||
PendingIntent | createPendingResult(int requestCode, Intent data, int flags) | |||||
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. | ||||||
final | void | dismissDialog(int id) | ||||
Dismiss a dialog that was previously shown via showDialog(int). | ||||||
boolean | dispatchKeyEvent(KeyEvent event) | |||||
Called to process key events. | ||||||
boolean | dispatchTouchEvent(MotionEvent ev) | |||||
Called to process touch screen events. | ||||||
boolean | dispatchTrackballEvent(MotionEvent ev) | |||||
Called to process trackball events. | ||||||
View | findViewById(int id) | |||||
Finds a view that was identified by the id attribute from the XML that was processed in onCreate(Bundle). | ||||||
void | finish() | |||||
Call this when your activity is done and should be closed. | ||||||
void | finishActivity(int requestCode) | |||||
Force finish another activity that you had previously started with startActivityForResult(Intent, int). | ||||||
void | finishActivityFromChild(Activity child, int requestCode) | |||||
This is called when a child activity of this one calls its finishActivity(). | ||||||
void | finishFromChild(Activity child) | |||||
This is called when a child activity of this one calls its finish() method. | ||||||
final | Application | getApplication() | ||||
Return the application that owns this activity. | ||||||
ComponentName | getCallingActivity() | |||||
Return the name of the activity that invoked this activity. | ||||||
String | getCallingPackage() | |||||
Return the name of the package that invoked this activity. | ||||||
int | getChangingConfigurations() | |||||
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. | ||||||
ComponentName | getComponentName() | |||||
Returns complete component name of this activity. | ||||||
View | getCurrentFocus() | |||||
Calls getCurrentFocus() on the Window of this Activity to return the currently focused view. | ||||||
static | long | getInstanceCount() | ||||
Intent | getIntent() | |||||
Return the intent that started this activity. | ||||||
Object | getLastNonConfigurationInstance() | |||||
Retrieve the non-configuration instance data that was previously returned by onRetainNonConfigurationInstance(). | ||||||
LayoutInflater | getLayoutInflater() | |||||
Convenience for calling getLayoutInflater(). | ||||||
String | getLocalClassName() | |||||
Returns class name for this activity with the package prefix removed. | ||||||
MenuInflater | getMenuInflater() | |||||
Returns a MenuInflater with this context. | ||||||
final | Activity | getParent() | ||||
Return the parent activity if this view is an embedded child. | ||||||
SharedPreferences | getPreferences(int mode) | |||||
Retrieve a SharedPreferences object for accessing preferences that are private to this activity. | ||||||
int | getRequestedOrientation() | |||||
Return the current requested orientation of the activity. | ||||||
Object | getSystemService(String name) | |||||
Return the handle to a system-level service by name. | ||||||
int | getTaskId() | |||||
Return the identifier of the task this activity is in. | ||||||
final | CharSequence | getTitle() | ||||
final | int | getTitleColor() | ||||
final | int | getVolumeControlStream() | ||||
Gets the suggested audio stream whose volume should be changed by the harwdare volume controls. | ||||||
int | getWallpaperDesiredMinimumHeight() | |||||
Returns the desired minimum height for the wallpaper. | ||||||
int | getWallpaperDesiredMinimumWidth() | |||||
Returns the desired minimum width for the wallpaper. | ||||||
Window | getWindow() | |||||
Retrieve the current Window for the activity. | ||||||
WindowManager | getWindowManager() | |||||
Retrieve the window manager for showing custom windows. | ||||||
final | boolean | isChild() | ||||
Is this activity embedded inside of another activity? | ||||||
boolean | isFinishing() | |||||
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. | ||||||
boolean | isTaskRoot() | |||||
Return whether this activity is the root of a task. | ||||||
final | Cursor | managedQuery(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) | ||||
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. | ||||||
boolean | moveTaskToBack(boolean nonRoot) | |||||
Move the task containing this activity to the back of the activity stack. | ||||||
void | onConfigurationChanged(Configuration newConfig) | |||||
Called by the system when the device configuration changes while your activity is running. | ||||||
void | onContentChanged() | |||||
This hook is called whenever the content view of the screen changes (due to a call to Window.setContentView or Window.addContentView). | ||||||
boolean | onContextItemSelected(MenuItem item) | |||||
This hook is called whenever an item in a context menu is selected. | ||||||
void | onContextMenuClosed(Menu menu) | |||||
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). | ||||||
void | onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) | |||||
Called when a context menu for the view is about to be shown. |
||||||
CharSequence | onCreateDescription() | |||||
Generate a new description for this activity. | ||||||
boolean | onCreateOptionsMenu(Menu menu) | |||||
Initialize the contents of the Activity's standard options menu. | ||||||
boolean | onCreatePanelMenu(int featureId, Menu menu) | |||||
Default implementation of onCreatePanelMenu(int, Menu) for activities. | ||||||
View | onCreatePanelView(int featureId) | |||||
Default implementation of onCreatePanelView(int) for activities. | ||||||
boolean | onCreateThumbnail(Bitmap outBitmap, Canvas canvas) | |||||
Generate a new thumbnail for this activity. | ||||||
View | onCreateView(String name, Context context, AttributeSet attrs) | |||||
Stub implementation of onCreateView(String, Context, AttributeSet) used when inflating with the LayoutInflater returned by getSystemService(String). | ||||||
boolean | onKeyDown(int keyCode, KeyEvent event) | |||||
Called when a key was pressed down and not handled by any of the views inside of the activity. | ||||||
boolean | onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) | |||||
Default implementation of KeyEvent.Callback.onKeyMultiple(): always returns false (doesn't handle the event). | ||||||
boolean | onKeyUp(int keyCode, KeyEvent event) | |||||
Called when a key was released and not handled by any of the views inside of the activity. | ||||||
void | onLowMemory() | |||||
This is called when the overall system is running low on memory, and would like actively running process to try to tighten their belt. | ||||||
boolean | onMenuItemSelected(int featureId, MenuItem item) | |||||
Default implementation of onMenuItemSelected(int, MenuItem) for activities. | ||||||
boolean | onMenuOpened(int featureId, Menu menu) | |||||
Called when a panel's menu is opened by the user. | ||||||
boolean | onOptionsItemSelected(MenuItem item) | |||||
This hook is called whenever an item in your options menu is selected. | ||||||
void | onOptionsMenuClosed(Menu menu) | |||||
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). | ||||||
void | onPanelClosed(int featureId, Menu menu) | |||||
Default implementation of onPanelClosed(int, Menu) for activities. | ||||||
boolean | onPrepareOptionsMenu(Menu menu) | |||||
Prepare the Screen's standard options menu to be displayed. | ||||||
boolean | onPreparePanel(int featureId, View view, Menu menu) | |||||
Default implementation of onPreparePanel(int, View, Menu) for activities. | ||||||
Object | onRetainNonConfigurationInstance() | |||||
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. | ||||||
boolean | onSearchRequested() | |||||
This hook is called when the user signals the desire to start a search. | ||||||
boolean | onTouchEvent(MotionEvent event) | |||||
Called when a touch screen event was not handled by any of the views under it. | ||||||
boolean | onTrackballEvent(MotionEvent event) | |||||
Called when the trackball was moved and not handled by any of the views inside of the activity. | ||||||
void | onWindowAttributesChanged(WindowManager.LayoutParams params) | |||||
This is called whenever the current window attributes change. | ||||||
void | onWindowFocusChanged(boolean hasFocus) | |||||
Called when the current Window of the activity gains or loses focus. | ||||||
void | openContextMenu(View view) | |||||
Programmatically opens the context menu for a particular view . |
||||||
void | openOptionsMenu() | |||||
Programmatically opens the options menu. | ||||||
void | registerForContextMenu(View view) | |||||
Registers a context menu to be shown for the given view (multiple views can show the context menu). | ||||||
final | void | removeDialog(int id) | ||||
Removes any internal references to a dialog managed by this Activity. | ||||||
final | boolean | requestWindowFeature(int featureId) | ||||
Enable extended window features. | ||||||
final | void | runOnUiThread(Runnable action) | ||||
Runs the specified action on the UI thread. | ||||||
void | setContentView(int layoutResID) | |||||
Set the activity content from a layout resource. | ||||||
void | setContentView(View view, ViewGroup.LayoutParams params) | |||||
Set the activity content to an explicit view. | ||||||
void | setContentView(View view) | |||||
Set the activity content to an explicit view. | ||||||
final | void | setDefaultKeyMode(int mode) | ||||
Select the default key handling for this activity. | ||||||
final | void | setFeatureDrawable(int featureId, Drawable drawable) | ||||
Convenience for calling setFeatureDrawable(int, Drawable). | ||||||
final | void | setFeatureDrawableAlpha(int featureId, int alpha) | ||||
Convenience for calling setFeatureDrawableAlpha(int, int). | ||||||
final | void | setFeatureDrawableResource(int featureId, int resId) | ||||
Convenience for calling setFeatureDrawableResource(int, int). | ||||||
final | void | setFeatureDrawableUri(int featureId, Uri uri) | ||||
Convenience for calling setFeatureDrawableUri(int, Uri). | ||||||
void | setIntent(Intent newIntent) | |||||
Change the intent returned by getIntent(). | ||||||
void | setPersistent(boolean isPersistent) | |||||
Control whether this activity is required to be persistent. | ||||||
final | void | setProgress(int progress) | ||||
Sets the progress for the progress bars in the title. | ||||||
final | void | setProgressBarIndeterminate(boolean indeterminate) | ||||
Sets whether the horizontal progress bar in the title should be indeterminate (the circular is always indeterminate). | ||||||
final | void | setProgressBarIndeterminateVisibility(boolean visible) | ||||
Sets the visibility of the indeterminate progress bar in the title. | ||||||
final | void | setProgressBarVisibility(boolean visible) | ||||
Sets the visibility of the progress bar in the title. | ||||||
void | setRequestedOrientation(int requestedOrientation) | |||||
Change the desired orientation of this activity. | ||||||
final | void | setResult(int resultCode, Intent data) | ||||
Call this to set the result that your activity will return to its caller. | ||||||
final | void | setResult(int resultCode) | ||||
Call this to set the result that your activity will return to its caller. | ||||||
final | void | setSecondaryProgress(int secondaryProgress) | ||||
Sets the secondary progress for the progress bar in the title. | ||||||
void | setTitle(int titleId) | |||||
Change the title associated with this activity. | ||||||
void | setTitle(CharSequence title) | |||||
Change the title associated with this activity. | ||||||
void | setTitleColor(int textColor) | |||||
final | void | setVolumeControlStream(int streamType) | ||||
Suggests an audio stream whose volume should be changed by the hardware volume controls. | ||||||
final | void | showDialog(int id) | ||||
Show a dialog managed by this activity. | ||||||
void | startActivity(Intent intent) | |||||
Launch a new activity. | ||||||
void | startActivityForResult(Intent intent, int requestCode) | |||||
Launch an activity for which you would like a result when it finished. | ||||||
void | startActivityFromChild(Activity child, Intent intent, int requestCode) | |||||
This is called when a child activity of this one calls its startActivity(Intent) or startActivityForResult(Intent, int) method. | ||||||
boolean | startActivityIfNeeded(Intent intent, int requestCode) | |||||
A special variation to launch an activity only if a new activity instance is needed to handle the given Intent. | ||||||
void | startManagingCursor(Cursor c) | |||||
This method allows the activity to take care of managing the given Cursor's lifecycle for you based on the activity's lifecycle. | ||||||
boolean | startNextMatchingActivity(Intent intent) | |||||
Special version of starting an activity, for use when you are replacing other activity components. | ||||||
void | startSearch(String initialQuery, boolean selectInitialQuery, Bundle appSearchData, boolean globalSearch) | |||||
This hook is called to launch the search UI. | ||||||
void | stopManagingCursor(Cursor c) | |||||
Given a Cursor that was previously given to startManagingCursor(Cursor), stop the activity's management of that cursor. | ||||||
void | takeKeyEvents(boolean get) | |||||
Request that key events come to this activity. | ||||||
void | unregisterForContextMenu(View view) | |||||
Prevents a context menu to be shown for the given view. |
void | finalize() | |||||
Called by the virtual machine when there are no longer any (non-weak) references to the receiver. | ||||||
void | onActivityResult(int requestCode, int resultCode, Intent data) | |||||
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. | ||||||
void | onApplyThemeResource(Resources.Theme theme, int resid, boolean first) | |||||
Called by setTheme(int) and getTheme() to apply a theme resource to the current Theme object. | ||||||
void | onChildTitleChanged(Activity childActivity, CharSequence title) | |||||
void | onCreate(Bundle savedInstanceState) | |||||
Called when the activity is starting. | ||||||
Dialog | onCreateDialog(int id) | |||||
Callback for creating dialogs that are managed (saved and restored) for you by the activity. | ||||||
void | onDestroy() | |||||
Perform any final cleanup before an activity is destroyed. | ||||||
void | onNewIntent(Intent intent) | |||||
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). | ||||||
void | onPause() | |||||
Called as part of the activity lifecycle when an activity is going into the background, but has not (yet) been killed. | ||||||
void | onPostCreate(Bundle savedInstanceState) | |||||
Called when activity start-up is complete (after onStart() and onRestoreInstanceState(Bundle) have been called). | ||||||
void | onPostResume() | |||||
Called when activity resume is complete (after onResume() has been called). | ||||||
void | onPrepareDialog(int id, Dialog dialog) | |||||
Provides an opportunity to prepare a managed dialog before it is being shown. | ||||||
void | onRestart() | |||||
Called after onStart() when the current activity is being re-displayed to the user (the user has navigated back to it). | ||||||
void | onRestoreInstanceState(Bundle savedInstanceState) | |||||
This method is called after onStart() when the activity is being re-initialized from a previously saved state, given here in state. | ||||||
void | onResume() | |||||
Called after onRestoreInstanceState(Bundle), onRestart(), or onPause(), for your activity to start interacting with the user. | ||||||
void | onSaveInstanceState(Bundle outState) | |||||
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). | ||||||
void | onStart() | |||||
Called after onCreate(Bundle) or onStop() when the current activity is now being displayed to the user. | ||||||
void | onStop() | |||||
Called when you are no longer visible to the user. | ||||||
void | onTitleChanged(CharSequence title, int color) |
See android.app.SearchManager for more details.
See android.app.SearchManager for more details.
That is, the user does not need to hold down the menu key to execute menu shortcuts.
view | The desired content to display. |
---|---|
params | Layout parameters for the view. |
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, 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. |
id | The id of the managed dialog. |
---|
IllegalArgumentException | if the id was not previously shown via showDialog(int). |
---|
event | The key event. |
---|
ev | The touch screen event. |
---|
ev | The trackball event. |
---|
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. |
---|
child | The activity making the call. |
---|---|
requestCode | Request code that had been used to start the activity. |
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.
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.
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.
mode | Operating mode. Use MODE_PRIVATE for the default operation, MODE_WORLD_READABLE and MODE_WORLD_WRITEABLE to control permissions. |
---|
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.)
name | The name of the desired service. |
---|
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. |
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. |
---|
At the time that this function has been called, your Resources object will have been updated to return resource values matching the new configuration.
newConfig | The new device configuration. |
---|
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.
item | The context menu item that was selected. |
---|
menu | The context menu that is being closed. |
---|
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.
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.
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.
When you add items to the menu, you can implement the Activity's onOptionsItemSelected(MenuItem) method to handle them there.
menu | The options menu in which you place your items. |
---|
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.
outBitmap | The bitmap to contain the thumbnail. |
---|---|
canvas | Can be used to render into the bitmap. |
If the focused view didn't want this event, this method is called.
The default implementation handles KEYCODE_BACK to stop the activity and go back, and other default key handling if configured with setDefaultKeyMode(int).
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.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. 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.
Derived classes should call through to the base class for it to perform the default menu handling.
item | The menu item that was selected. |
---|
menu | The options menu as last shown or first initialized by onCreateOptionsMenu(). |
---|
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.
menu | The options menu as last shown or first initialized by onCreateOptionsMenu(). |
---|
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:
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.
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:
The default implementation simply calls startSearch(null, false, null, false), launching a local search.
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).
event | The touch screen event being processed. |
---|
event | The trackball event being processed. |
---|
hasFocus | Whether the window of this activity has focus. |
---|
view
.
The view
should have been added via
registerForContextMenu(View).
view | The view to show the context menu for. |
---|
view | The view that should show a context menu. |
---|
id | The id of the managed dialog. |
---|
featureId | The desired feature as defined in Window. |
---|
action | the action to run on the UI thread |
---|
layoutResID | Resource ID to be inflated. |
---|
view | The desired content to display. |
---|---|
params | Layout parameters for the view. |
view | The desired content to display. |
---|
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.
mode | The desired default key mode constant. |
---|
newIntent | The new Intent object to return from getIntent |
---|
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).
isPersistent | Control whether the current activity must be persistent, true if so, false for the normal behavior. |
---|
In order for the progress bar to be shown, the feature must be requested via requestWindowFeature(int).
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. |
---|
In order for the progress bar to be shown, the feature must be requested via requestWindowFeature(int).
indeterminate | Whether the horizontal progress bar should be indeterminate. |
---|
In order for the progress bar to be shown, the feature must be requested via requestWindowFeature(int).
visible | Whether to show the progress bars in the title. |
---|
In order for the progress bar to be shown, the feature must be requested via requestWindowFeature(int).
visible | Whether to show the progress bars in the title. |
---|
requestedOrientation | An orientation constant as used in ActivityInfo.screenOrientation. |
---|
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. |
resultCode | The result code to propagate back to the originating activity, often RESULT_CANCELED or RESULT_OK |
---|
In order for the progress bar to be shown, the feature must be requested via requestWindowFeature(int).
secondaryProgress | The secondary progress for the progress bar. Valid ranges are from 0 to 10000 (both inclusive). |
---|
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.
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. |
---|
id | The id of the managed dialog. |
---|
This method throws ActivityNotFoundException if there was no Activity found to run the given Intent.
intent | The intent to start. |
---|
android.content.ActivityNotFoundException |
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.
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.
This method throws ActivityNotFoundException if there was no Activity found to run the given Intent.
intent | The intent to start. |
---|---|
requestCode | If >= 0, this code will be returned in onActivityResult() when the activity exits. |
android.content.ActivityNotFoundException |
This method throws ActivityNotFoundException if there was no Activity found to run the given Intent.
child | The activity making the call. |
---|---|
intent | The intent to start. |
requestCode | Reply request code. < 0 if reply is not requested. |
android.content.ActivityNotFoundException |
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.
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). |
c | The Cursor to be managed. |
---|
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. |
---|
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.
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, no search will be launched. If true, this will always launch a platform-global (e.g. web-based) search instead. |
c | The Cursor that was being managed. |
---|
view | The view that should stop showing a context menu. |
---|
Note: The virtual machine assumes that the implementation in class Object is empty.
Throwable |
---|
You will receive this call immediately before onResume() when your activity is re-starting.
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"). |
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. |
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.
Derived classes must call through to the super class's implementation of this method. If they do not, an exception will be thrown.
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. |
---|
id | The id of the dialog. |
---|
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.
An activity will always be paused before receiving a new intent, so you can count on onResume() being called after this method.
Note that getIntent() still returns the original Intent. You can use setIntent(Intent) to update it to this new Intent.
intent | The new intent that was started for the activity. |
---|
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.
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.
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.
Derived classes must call through to the super class's implementation of this method. If they do not, an exception will be thrown.
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. |
---|
Derived classes must call through to the super class's implementation of this method. If they do not, an exception will be thrown.
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.
id | The id of the managed dialog. |
---|---|
dialog | The dialog. |
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().
Derived classes must call through to the super class's implementation of this method. If they do not, an exception will be thrown.
This method is called between onStart() and onPostCreate(Bundle).
savedInstanceState | the data most recently supplied in onSaveInstanceState(Bundle). |
---|
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).
Derived classes must call through to the super class's implementation of this method. If they do not, an exception will be thrown.
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.
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().
outState | Bundle in which to place your saved state. |
---|
Derived classes must call through to the super class's implementation of this method. If they do not, an exception will be thrown.
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.
Derived classes must call through to the super class's implementation of this method. If they do not, an exception will be thrown.
Copyright 2007 Google Inc. | Build 110632-110632 - 22 Sep 2008 13:34 |