java.lang.Object
   ↳ android.content.Context
     ↳ android.content.ContextWrapper
       ↳ android.view.ContextThemeWrapper
         ↳ android.app.Activity
Known Direct Subclasses
Known Indirect Subclasses

Class Overview

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:

  • onCreate(Bundle) is where you initialize your activity. Most importantly, here you will usually call setContentView(int) with a layout resource defining your UI, and using findViewById(int) to retrieve the widgets in that UI that you need to interact with programmatically.
  • onPause() is where you deal with the user leaving your activity. Most importantly, any changes made by the user should at this point be committed (usually to the ContentProvider holding the data).

To be of use with Context.startActivity(), all activity classes must have a corresponding <activity> declaration in their package's AndroidManifest.xml.

Topics covered here:

  1. Fragments
  2. Activity Lifecycle
  3. Configuration Changes
  4. Starting Activities and Getting Results
  5. Saving Persistent State
  6. Permissions
  7. Process Lifecycle

Developer Guides

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. For a detailed perspective on the structure of an Android application and how activities behave, please read the Application Fundamentals and Tasks and Back Stack developer guides.

You can also find a detailed discussion about how to create activities in the Activities developer guide.

Fragments

Starting with HONEYCOMB, Activity implementations can make use of the Fragment class to better modularize their code, build more sophisticated user interfaces for larger screens, and help scale their application between small and large screens.

Activity Lifecycle

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:

  • If an activity in the foreground of the screen (at the top of the stack), it is active or running.
  • If an activity has lost focus but is still visible (that is, a new non-full-sized or transparent activity has focus on top of your activity), it is paused. A paused activity is completely alive (it maintains all state and member information and remains attached to the window manager), but can be killed by the system in extreme low memory situations.
  • If an activity is completely obscured by another activity, it is stopped. It still retains all state and member information, however, it is no longer visible to the user so its window is hidden and it will often be killed by the system when memory is needed elsewhere.
  • If an activity is paused or stopped, the system can drop the activity from memory by either asking it to finish, or simply killing its process. When it is displayed again to the user, it must be completely restarted and restored to its previous state.

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.

State diagram for an Android Activity Lifecycle.

There are three key loops you may be interested in monitoring within your activity:

  • The entire lifetime of an activity happens between the first call to onCreate(Bundle) through to a single final call to onDestroy(). An activity will do all setup of "global" state in onCreate(), and release all remaining resources in onDestroy(). For example, if it has a thread running in the background to download data from the network, it may create that thread in onCreate() and then stop the thread in onDestroy().
  • The visible lifetime of an activity happens between a call to onStart() until a corresponding call to onStop(). During this time the user can see the activity on-screen, though it may not be in the foreground and interacting with the user. Between these two methods you can maintain resources that are needed to show the activity to the user. For example, you can register a BroadcastReceiver in onStart() to monitor for changes that impact your UI, and unregister it in onStop() when the user an no longer see what you are displaying. The onStart() and onStop() methods can be called multiple times, as the activity becomes visible and hidden to the user.
  • The foreground lifetime of an activity happens between a call to onResume() until a corresponding call to onPause(). During this time the activity is in front of all other activities and interacting with the user. An activity can frequently go between the resumed and paused states -- for example when the device goes to sleep, when an activity result is delivered, when a new intent is delivered -- so the code in these methods should be fairly lightweight.

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

No onStart()
     onRestart() Called after your activity has been stopped, prior to it being started again.

Always followed by onStart()

No onStart()
onStart() Called when the activity is becoming visible to the user.

Followed by onResume() if the activity comes to the foreground, or onStop() if it becomes hidden.

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

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 onResume() if the activity returns back to the front, or onStop() if it becomes invisible to the user.

Pre-HONEYCOMB onResume() or
onStop()
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 onRestart() if this activity is coming back to interact with the user, or onDestroy() if this activity is going away.

Yes onRestart() or
onDestroy()
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 latter is not part of the lifecycle callbacks, so will not be called in every situation as described in its documentation.

Be aware that these semantics will change slightly between applications targeting platforms starting with HONEYCOMB vs. those targeting prior platforms. Starting with Honeycomb, an application is not in the killable state until its onStop() has returned. This impacts when onSaveInstanceState(Bundle) may be called (it may be safely called after onPause() and allows and application to safely wait until onStop() to save persistent state.

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

Configuration Changes

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.

Starting Activities and Getting Results

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));
             }
         }
     }
 }
 

Saving Persistent State

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. Canceling 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();
     }
 }
 

Permissions

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 and Permissions document for more information on permissions and security in general.

Process Lifecycle

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

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

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

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

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

Summary

Constants
int DEFAULT_KEYS_DIALER Use with setDefaultKeyMode(int) to launch the dialer during default key handling.
int DEFAULT_KEYS_DISABLE Use with setDefaultKeyMode(int) to turn off default handling of keys.
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.

int DEFAULT_KEYS_SEARCH_LOCAL Use with setDefaultKeyMode(int) to specify that unhandled keystrokes will start an application-defined search.
int DEFAULT_KEYS_SHORTCUT Use with setDefaultKeyMode(int) to execute a menu shortcut in default key handling.
int RESULT_CANCELED Standard activity result: operation canceled.
int RESULT_FIRST_USER Start of user-defined activity results.
int RESULT_OK Standard activity result: operation succeeded.
[Expand]
Inherited Constants
From class android.content.Context
From interface android.content.ComponentCallbacks2
Fields
protected static final int[] FOCUSED_STATE_SET
Public Constructors
Activity()
Public Methods
void addContentView(View view, ViewGroup.LayoutParams params)
Add an additional content view to the activity.
void closeContextMenu()
Programmatically closes the most recently opened context menu, if showing.
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)
This method is deprecated. Use the new DialogFragment class with FragmentManager instead; this is also available on older platforms through the Android compatibility package.
boolean dispatchGenericMotionEvent(MotionEvent ev)
Called to process generic motion events.
boolean dispatchKeyEvent(KeyEvent event)
Called to process key events.
boolean dispatchKeyShortcutEvent(KeyEvent event)
Called to process a key shortcut event.
boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event)
Called to process population of AccessibilityEvents.
boolean dispatchTouchEvent(MotionEvent ev)
Called to process touch screen events.
boolean dispatchTrackballEvent(MotionEvent ev)
Called to process trackball events.
void dump(String prefix, FileDescriptor fd, PrintWriter writer, String[] args)
Print the Activity's state into the given stream.
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.
ActionBar getActionBar()
Retrieve a reference to this activity's ActionBar.
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.
FragmentManager getFragmentManager()
Return the FragmentManager for interacting with fragments associated with this activity.
Intent getIntent()
Return the intent that started this activity.
Object getLastNonConfigurationInstance()
This method is deprecated. Use the new Fragment API setRetainInstance(boolean) instead; this is also available on older platforms through the Android compatibility package.
LayoutInflater getLayoutInflater()
Convenience for calling getLayoutInflater().
LoaderManager getLoaderManager()
Return the LoaderManager for this fragment, creating it if needed.
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.
Window getWindow()
Retrieve the current Window for the activity.
WindowManager getWindowManager()
Retrieve the window manager for showing custom windows.
boolean hasWindowFocus()
Returns true if this activity's main window currently has window focus.
void invalidateOptionsMenu()
Declare that the options menu has changed, so should be recreated.
boolean isChangingConfigurations()
Check to see whether this activity is in the process of being destroyed in order to be recreated with a new configuration.
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)
This method is deprecated. Use CursorLoader instead.
boolean moveTaskToBack(boolean nonRoot)
Move the task containing this activity to the back of the activity stack.
void onActionModeFinished(ActionMode mode)
Notifies the activity that an action mode has finished.
void onActionModeStarted(ActionMode mode)
Notifies the Activity that an action mode has been started.
void onAttachFragment(Fragment fragment)
Called when a Fragment is being attached to this activity, immediately after the call to its Fragment.onAttach() method and before Fragment.onCreate().
void onAttachedToWindow()
Called when the main window associated with the activity has been attached to the window manager.
void onBackPressed()
Called when the activity has detected the user's press of the back key.
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(View parent, String name, Context context, AttributeSet attrs)
Standard implementation of onCreateView(View, String, Context, AttributeSet) used when inflating with the LayoutInflater returned by getSystemService(String).
View onCreateView(String name, Context context, AttributeSet attrs)
Standard implementation of onCreateView(String, Context, AttributeSet) used when inflating with the LayoutInflater returned by getSystemService(String).
void onDetachedFromWindow()
Called when the main window associated with the activity has been detached from the window manager.
boolean onGenericMotionEvent(MotionEvent event)
Called when a generic motion event was not handled by any of the views inside of the activity.
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 onKeyLongPress(int keyCode, KeyEvent event)
Default implementation of KeyEvent.Callback.onKeyLongPress(): always returns false (doesn't handle the event).
boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event)
Default implementation of KeyEvent.Callback.onKeyMultiple(): always returns false (doesn't handle the event).
boolean onKeyShortcut(int keyCode, KeyEvent event)
Called when a key shortcut event is not handled by any of the views in the Activity.
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()
This method is deprecated. Use the new Fragment API setRetainInstance(boolean) instead; this is also available on older platforms through the Android compatibility package.
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 onTrimMemory(int level)
Called when the operating system has determined that it is a good time for a process to trim unneeded memory from its process.
void onUserInteraction()
Called whenever a key, touch, or trackball event is dispatched to 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.
ActionMode onWindowStartingActionMode(ActionMode.Callback callback)
Give the Activity a chance to control the UI for an action mode requested by the system.
void openContextMenu(View view)
Programmatically opens the context menu for a particular view.
void openOptionsMenu()
Programmatically opens the options menu.
void overridePendingTransition(int enterAnim, int exitAnim)
Call immediately after one of the flavors of startActivity(Intent) or finish() to specify an explicit transition animation to perform next.
void recreate()
Cause this Activity to be recreated with a new instance.
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)
This method is deprecated. Use the new DialogFragment class with FragmentManager instead; this is also available on older platforms through the Android compatibility package.
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)
Set the activity content to an explicit view.
void setContentView(View view, ViewGroup.LayoutParams params)
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 setFinishOnTouchOutside(boolean finish)
Sets whether this activity is finished when touched outside its window's bounds.
void setIntent(Intent newIntent)
Change the intent returned by getIntent().
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)
Call this to set the result that your activity will return to its caller.
final void setResult(int resultCode, Intent data)
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)
void setVisible(boolean visible)
Control whether this activity's main window is visible.
final void setVolumeControlStream(int streamType)
Suggests an audio stream whose volume should be changed by the hardware volume controls.
final boolean showDialog(int id, Bundle args)
This method is deprecated. Use the new DialogFragment class with FragmentManager instead; this is also available on older platforms through the Android compatibility package.
final void showDialog(int id)
This method is deprecated. Use the new DialogFragment class with FragmentManager instead; this is also available on older platforms through the Android compatibility package.
ActionMode startActionMode(ActionMode.Callback callback)
Start an action mode.
void startActivities(Intent[] intents)
Launch a new 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.
void startActivityFromFragment(Fragment fragment, Intent intent, int requestCode)
This is called when a Fragment in this activity 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 startIntentSender(IntentSender intent, Intent fillInIntent, int flagsMask, int flagsValues, int extraFlags)
Like startActivity(Intent), but taking a IntentSender to start; see startIntentSenderForResult(IntentSender, int, Intent, int, int, int) for more information.
void startIntentSenderForResult(IntentSender intent, int requestCode, Intent fillInIntent, int flagsMask, int flagsValues, int extraFlags)
Like startActivityForResult(Intent, int), but allowing you to use a IntentSender to describe the activity to be started.
void startIntentSenderFromChild(Activity child, IntentSender intent, int requestCode, Intent fillInIntent, int flagsMask, int flagsValues, int extraFlags)
void startManagingCursor(Cursor c)
This method is deprecated. Use the new CursorLoader class with LoaderManager instead; this is also available on older platforms through the Android compatibility package.
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)
This method is deprecated. Use the new CursorLoader class with LoaderManager instead; this is also available on older platforms through the Android compatibility package.
void takeKeyEvents(boolean get)
Request that key events come to this activity.
void triggerSearch(String query, Bundle appSearchData)
Similar to startSearch(String, boolean, Bundle, boolean), but actually fires off the search query after invoking the search dialog.
void unregisterForContextMenu(View view)
Prevents a context menu to be shown for the given view.
Protected Methods
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)
This method is deprecated. Old no-arguments version of onCreateDialog(int, Bundle).
Dialog onCreateDialog(int id, Bundle args)
This method is deprecated. Use the new DialogFragment class with FragmentManager instead; this is also available on older platforms through the Android compatibility package.
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)
This method is deprecated. Old no-arguments version of onPrepareDialog(int, Dialog, Bundle).
void onPrepareDialog(int id, Dialog dialog, Bundle args)
This method is deprecated. Use the new DialogFragment class with FragmentManager instead; this is also available on older platforms through the Android compatibility package.
void onRestart()
Called after onStop() 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 savedInstanceState.
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 after onRestart() when the activity had been stopped, but is now again being displayed to the user.
void onStop()
Called when you are no longer visible to the user.
void onTitleChanged(CharSequence title, int color)
void onUserLeaveHint()
Called as part of the activity lifecycle when an activity is about to go into the background as the result of user choice.
[Expand]
Inherited Methods
From class android.view.ContextThemeWrapper
From class android.content.ContextWrapper
From class android.content.Context
From class java.lang.Object
From interface android.content.ComponentCallbacks
From interface android.content.ComponentCallbacks2
From interface android.view.KeyEvent.Callback
From interface android.view.LayoutInflater.Factory
From interface android.view.LayoutInflater.Factory2
From interface android.view.View.OnCreateContextMenuListener
From interface android.view.Window.Callback

Constants

public static final int DEFAULT_KEYS_DIALER

Since: API Level 1

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

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.

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.

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.

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.

Constant Value: 2 (0x00000002)

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)

Fields

protected static final int[] FOCUSED_STATE_SET

Since: API Level 1

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

public final void dismissDialog (int id)

Since: API Level 1

This method is deprecated.
Use the new DialogFragment class with FragmentManager instead; this is also available on older platforms through the Android compatibility package.

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

public boolean dispatchGenericMotionEvent (MotionEvent ev)

Since: API Level 12

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

Parameters
ev The generic motion event.
Returns
  • boolean Return true if this event was consumed.

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 dispatchKeyShortcutEvent (KeyEvent event)

Since: API Level 11

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

Parameters
event The key shortcut event.
Returns
  • 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 void dump (String prefix, FileDescriptor fd, PrintWriter writer, String[] args)

Since: API Level 11

Print the Activity's state into the given stream. This gets invoked if you run "adb shell dumpsys activity ".

Parameters
prefix Desired prefix to prepend at each line of output.
fd The raw file descriptor that the dump is being sent to.
writer The PrintWriter to which you should dump your state. This will be closed for you after you return.
args additional arguments to the dump request.

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

public ActionBar getActionBar ()

Since: API Level 11

Retrieve a reference to this activity's ActionBar.

Returns
  • The Activity's ActionBar, or null if it does not have one.

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.

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.

public FragmentManager getFragmentManager ()

Since: API Level 11

Return the FragmentManager for interacting with fragments associated with this activity.

public Intent getIntent ()

Since: API Level 1

Return the intent that started this activity.

public Object getLastNonConfigurationInstance ()

Since: API Level 1

This method is deprecated.
Use the new Fragment API setRetainInstance(boolean) instead; this is also available on older platforms through the Android compatibility package.

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

public LayoutInflater getLayoutInflater ()

Since: API Level 1

Convenience for calling getLayoutInflater().

public LoaderManager getLoaderManager ()

Since: API Level 11

Return the LoaderManager for this fragment, creating it if needed.

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.

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

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.
UI_MODE_SERVICE ("uimode")
An UiModeManager for controlling UI modes.
DOWNLOAD_SERVICE ("download")
A DownloadManager for requesting HTTP downloads

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.

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.

public void invalidateOptionsMenu ()

Since: API Level 11

Declare that the options menu has changed, so should be recreated. The onCreateOptionsMenu(Menu) method will be called the next time it needs to be displayed.

public boolean isChangingConfigurations ()

Since: API Level 11

Check to see whether this activity is in the process of being destroyed in order to be recreated with a new configuration. This is often used in onStop() to determine whether the state needs to be cleaned up or will be passed on to the next instance of the activity via onRetainNonConfigurationInstance().

Returns
  • If the activity is being torn down in order to be recreated with a new configuration, returns true; else returns false.

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

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

This method is deprecated.
Use CursorLoader instead.

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. If you are targeting HONEYCOMB or later, consider instead using LoaderManager instead, available via getLoaderManager().

Warning: Do not call close() on a cursor obtained using this method, because the activity will do that for you at the appropriate time. However, if you call stopManagingCursor(Cursor) on a cursor from a managed query, the system will not automatically close the cursor and, in that case, you must call close().

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

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 onActionModeFinished (ActionMode mode)

Since: API Level 11

Notifies the activity that an action mode has finished. Activity subclasses overriding this method should call the superclass implementation.

Parameters
mode The action mode that just finished.

public void onActionModeStarted (ActionMode mode)

Since: API Level 11

Notifies the Activity that an action mode has been started. Activity subclasses overriding this method should call the superclass implementation.

Parameters
mode The new action mode.

public void onAttachFragment (Fragment fragment)

Since: API Level 11

Called when a Fragment is being attached to this activity, immediately after the call to its Fragment.onAttach() method and before Fragment.onCreate().

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.

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.

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

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

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.

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.

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 returns fails and does not draw a thumbnail; this will result in the platform creating its own thumbnail if needed.

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.

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

Since: API Level 11

Standard implementation of onCreateView(View, String, Context, AttributeSet) used when inflating with the LayoutInflater returned by getSystemService(String). This implementation handles tags to embed fragments inside of the activity.

Parameters
parent The parent that the created view will be placed in; note that this may be null.
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.

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

Since: API Level 1

Standard implementation of onCreateView(String, Context, AttributeSet) used when inflating with the LayoutInflater returned by getSystemService(String). This implementation does nothing and is for pre-HONEYCOMB apps. Newer apps should use onCreateView(View, String, Context, AttributeSet).

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.

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.

public boolean onGenericMotionEvent (MotionEvent event)

Since: API Level 12

Called when a generic motion event was not handled by any of the views inside of the activity.

Generic motion events describe joystick movements, mouse hovers, track pad touches, scroll wheel movements and other input events. The source of the motion event specifies the class of input that was received. Implementations of this method must examine the bits in the source before processing the event. The following code example shows how this is done.

Generic motion events with source class SOURCE_CLASS_POINTER are delivered to the view under the pointer. All other generic motion events are delivered to the focused view.

See onGenericMotionEvent(MotionEvent) for an example of how to handle this event.

Parameters
event The generic motion 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 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.

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 onKeyShortcut (int keyCode, KeyEvent event)

Since: API Level 11

Called when a key shortcut event is not handled by any of the views in the Activity. Override this method to implement global key shortcuts for the Activity. Key shortcuts can also be implemented by setting the shortcut property of menu items.

Parameters
keyCode The value in event.getKeyCode().
event Description of the key event.
Returns
  • True if the key shortcut was handled.

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.

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.

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

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.

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.

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

This method is deprecated.
Use the new Fragment API setRetainInstance(boolean) instead; this is also available on older platforms through the Android compatibility package.

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. If you are targeting HONEYCOMB or later, consider instead using a Fragment with Fragment.setRetainInstance(boolean.

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. In particular, no messages will be dispatched during this time (when the returned object does not have an activity to be associated with).
  • 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.

The guarantee of no message handling during the switch to the next activity simplifies use with active objects. For example if your retained state is an AsyncTask you are guaranteed that its call back functions (like onPostExecute(Result)) will not be called from the call here until you execute the next instance's onCreate(Bundle). (Note however that there is of course no such guarantee for doInBackground(Params...) since that is running in a separate thread.)

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

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.

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 onTrimMemory (int level)

Since: API Level 14

Called when the operating system has determined that it is a good time for a process to trim unneeded memory from its process. This will happen for example when it goes in the background and there is not enough memory to keep as many background processes running as desired.

Parameters
level The context of the trim, giving a hint of the amount of trimming the application may like to perform. May be TRIM_MEMORY_COMPLETE, TRIM_MEMORY_MODERATE, TRIM_MEMORY_BACKGROUND, or TRIM_MEMORY_UI_HIDDEN.

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.

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.

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.

public ActionMode onWindowStartingActionMode (ActionMode.Callback callback)

Since: API Level 11

Give the Activity a chance to control the UI for an action mode requested by the system.

Note: If you are looking for a notification callback that an action mode has been started for this activity, see onActionModeStarted(ActionMode).

Parameters
callback The callback that should control the new action mode
Returns
  • The new action mode, or null if the activity does not want to provide special handling for this action mode. (It will be handled by the system.)

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

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.

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 t