Activity SDK文档

来源:互联网 发布:python 卷积函数 编辑:程序博客网 时间:2024/05/17 03:34

public class

Activity

extends ContextThemeWrapper
implements
ComponentCallbacks KeyEvent.Callback LayoutInflater.Factory2 View.OnCreateContextMenuListener Window.Callback

java.lang.Object

   

android.content.Context

 

   

android.content.ContextWrapper

 

 

   

android.view.ContextThemeWrapper

 

 

 

   

android.app.Activity

 

http://developer.android.com/assets/images/triangle-closed.pngKnown Direct Subclasses

AccountAuthenticatorActivity, ActivityGroup, AliasActivity, ExpandableListActivity, ListActivity, NativeActivity

AccountAuthenticatorActivity

Base class for implementing an Activity that is used to help implement an AbstractAccountAuthenticator. 

ActivityGroup

A screen that contains and runs multiple embedded activities. 

AliasActivity

Stub activity that launches another activity (and then finishes itself) based on information in its component's manifest meta-data. 

ExpandableListActivity

An activity that displays an expandable list of items by binding to a data source implementing the ExpandableListAdapter, and exposes event handlers when the user selects an item. 

ListActivity

An activity that displays a list of items by binding to a data source such as an array or Cursor, and exposes event handlers when the user selects an item. 

NativeActivity

Convenience for implementing an activity that will be implemented purely in native code. 

 

http://developer.android.com/assets/images/triangle-closed.pngKnown Indirect Subclasses

LauncherActivity, PreferenceActivity, TabActivity

LauncherActivity

Displays a list of all activities which can be performed for a given intent. 

PreferenceActivity

This is the base class for an activity to show a hierarchy of preferences to the user. 

TabActivity

An activity that contains and runs multiple embedded activities or views. 

Class Overview

An activity is a single, focused thingthat the user can do. Almost all activities interact with the user, so theActivity class takes care of creating a window for you in which you can placeyour UI with setContentView(View). While activities are often presentedto the user as full-screen windows, they can also be used in other ways: asfloating windows (via a theme with windowIsFloating set) or embedded inside of anotheractivity (using ActivityGroup). There are two methods almost allsubclasses 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 yourUI, and using findViewById(int) to retrieve the widgets in that UI thatyou need to interact with programmatically.

·        onPause() is where you deal with the user leavingyour activity. Most importantly, any changes made by the user should at thispoint be committed (usually to the ContentProvider holding the data).

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

The Activity class is an important partof an application's overall lifecycle, and the way activities are launched andput together is a fundamental part of the platform's application model. For adetailed perspective on the structure of an Android application and howactivities behave, please read the Application Fundamentals and Tasks and Back Stack documents.

You can also find a detailed discussionabout how to create activities in the Activities document.

Topics covered here:

1.     Fragments

2.     Activity Lifecycle

3.     Configuration Changes

4.     Starting Activities andGetting Results

5.     Saving Persistent State

6.     Permissions

7.     Process Lifecycle

Fragments

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

Activity Lifecycle

Activities in the system are managed asan activity stack. When a new activity is started, it isplaced on the top of the stack and becomes the running activity -- the previousactivity always remains below it in the stack, and will not come to theforeground again until the new activity exits.

An activity has essentially four states:

·        If an activity in the foreground of the screen (at thetop of the stack), it is active or running.

·        If an activity has lost focus but is still visible (thatis, a new non-full-sized or transparent activity has focus on top of youractivity), it is paused. A paused activity is completely alive (it maintains allstate and member information and remains attached to the window manager), butcan be killed by the system in extreme low memory situations.

·        If an activity is completely obscured by anotheractivity, 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 itwill often be killed by the system when memory is needed elsewhere.

·        If an activity is paused or stopped, the system can dropthe activity from memory by either asking it to finish, or simply killing itsprocess. When it is displayed again to the user, it must be completelyrestarted and restored to its previous state.

The following diagram shows theimportant state paths of an Activity. The square rectangles represent callbackmethods you can implement to perform operations when the Activity moves betweenstates. 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 beinterested in monitoring within your activity:

·        The entire lifetime of an activity happens betweenthe 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 inonDestroy(). For example, if it has a thread running in the background todownload data from the network, it may create that thread in onCreate() andthen stop the thread in onDestroy().

·        The visible lifetime of an activity happensbetween a call to onStart() until a corresponding call to onStop(). During this time the user can see theactivity on-screen, though it may not be in the foreground and interacting withthe user. Between these two methods you can maintain resources that are neededto show the activity to the user. For example, you can register a BroadcastReceiver in onStart() to monitor for changes thatimpact your UI, and unregister it in onStop() when the user an no longer seewhat you are displaying. The onStart() and onStop() methods can be calledmultiple times, as the activity becomes visible and hidden to the user.

·        The foreground lifetime of an activity happensbetween a call to onResume() until a corresponding call to onPause(). During this time the activity is infront of all other activities and interacting with the user. An activity canfrequently go between the resumed and paused states -- for example when thedevice goes to sleep, when an activity result is delivered, when a new intentis delivered -- so the code in these methods should be fairly lightweight.

The entire lifecycle of an activity isdefined by the following Activity methods. All of these are hooks that you canoverride to do appropriate work when the activity changes state. All activitieswill implement onCreate(Bundle) to do their initial setup; many willalso implement onPause() to commit changes to data and otherwiseprepare to stop interacting with the user. You should always call up to yoursuperclass when implementing these methods.

 public class Activity extends ApplicationContext {
     
protected void onCreate(BundlesavedInstanceState);

     
protected void onStart();
     
     
protected void onRestart();

     
protected void onResume();

     
protected void onPause();

     
protected void onStop();

     
protected void onDestroy();
 
}
 

In general the movement through anactivity'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 inthe above table -- for those methods that are marked as being killable, afterthat method returns the process hosting the activity may killed by the system at any time without another line of its code beingexecuted. 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 activityin such a background state, allowing you to save away any dynamic instancestate 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 thelifecycle of a process is tied to the activities it is hosting. Note that it isimportant to save persistent data in onPause() instead of onSaveInstanceState(Bundle) because the later is not part of thelifecycle callbacks, so will not be called in every situation as described inits documentation.

Be aware that these semantics willchange 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 calledafter onPause() and allows and application to safelywait until onStop() to save persistent state.

For those methods that are not marked asbeing killable, the activity's process will not be killed by the systemstarting 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 ofonResume().

Configuration Changes

If the configuration of the device (asdefined by the Resources.Configuration class) changes, then anythingdisplaying a user interface will need to update to match that configuration.Because Activity is the primary mechanism for interacting with the user, itincludes special support for handling configuration changes.

Unless you specify otherwise, aconfiguration change (such as a change in screen orientation, language, inputdevices, etc) will cause your current activity to be destroyed, going through the normal activitylifecycle process of onPause(), onStop(), and onDestroy() as appropriate. If the activity hadbeen in the foreground or visible to the user, once onDestroy() is called in that instance then a newinstance of the activity will be created, with whatever savedInstanceState theprevious instance had generated from onSaveInstanceState(Bundle).

This is done because any applicationresource, including layout files, can change based on any configuration value.Thus the only safe way to handle a configuration change is to re-retrieve allresources, including layouts, drawables, and strings. Because activities mustalready 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 newconfiguration.

In some special cases, you may want tobypass restarting of your activity based on one or more types of configurationchanges. This is done with the android:configChanges attribute in its manifest. For anytypes of configuration changes you say that you handle there, you will receivea call to your current activity's onConfigurationChanged(Configuration) method instead of being restarted. If aconfiguration change involves any that you do not handle, however, the activitywill 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 singleargument, an Intent, which describes the activity to beexecuted.

Sometimes you want to get a result backfrom an activity when it ends. For example, you may start an activity that letsthe user pick a person in a list of contacts; when it ends, it returns theperson that was selected. To do this, you call the startActivityForResult(Intent,int) version with a second integer parameter identifying the call. The resultwill 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. Itmust always supply a result code, which can be the standard resultsRESULT_CANCELED, RESULT_OK, or any custom values starting at RESULT_FIRST_USER.In addition, it can optionally return back an Intent containing any additionaldata it wants. All of this information appears back on the parent's Activity.onActivityResult(), along with the integer identifier it originallysupplied.

If a child activity fails for any reason(such as crashing), the parent activity will receive a result with the codeRESULT_CANCELED.

 public class MyActivity extends Activity {
     
...

     
static final intPICK_CONTACT_REQUEST = 0;

     
protected boolean onKeyDown(int keyCode, KeyEvent event) {
         
if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER) {
             
// When the usercenter 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 waspicked.  Here we will just display it
                 
// to the user.
                 startActivity
(new Intent(Intent.ACTION_VIEW, data));
             
}
         
}
     
}
 
}
 

Saving Persistent State

There are generally two kinds ofpersistent 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 userpreferences.

For content provider data, we suggestthat activities use a "edit in place" user model. That is, any editsa user makes are effectively made immediately without requiring an additionalconfirmation step. Supporting this model is generally a simple matter offollowing two rules:

·        When creating a new document, the backing database entryor file for it is created immediately. For example, if the user chooses towrite a new e-mail, a new entry for that e-mail is created as soon as theystart entering data, so that if they go to any other activity after that pointthis e-mail will now appear in the list of drafts.

·        When an activity's onPause() method iscalled, it should commit to the backing content provider or file any changesthe user has made. This ensures that those changes will be seen by any otheractivity that is about to run. You will probably want to commit your data evenmore aggressively at key times during your activity's lifecycle: for examplebefore starting a new activity, before finishing your own activity, when theuser switches between input fields, etc.

This model is designed to prevent dataloss when a user is navigating between activities, and allows the system tosafely kill an activity (because system resources are needed somewhere else) atany time after it has been paused. Note this implies that the user pressingBACK from your activity does not mean "cancel" -- it means toleave the activity with its current contents saved away. Canceling edits in anactivity must be provided through some other mechanism, such as an explicit"revert" or "undo" option.

See the content package for more information about contentproviders. These are a key aspect of how different activities invoke andpropagate data between themselves.

The Activity class also provides an APIfor managing internal persistent state associated with an activity. This can beused, for example, to remember the user's preferred initial display in acalendar (day view or week view) or the user's default home page in a webbrowser.

Activity persistent state is managedwith the method getPreferences(int), allowing you to retrieve and modify aset of name/value pairs associated with the activity. To use preferences thatare shared across multiple application components (activities, receivers,services, providers), you can use the underlying Context.getSharedPreferences() method to retrieve a preferences objectstored under a specific name. (Note that it is not possible to share settingsdata across application packages -- for that you will need a content provider.)

Here is an excerpt from a calendaractivity 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(BundlesavedInstanceState) {
         
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 particularActivity can be enforced when it is declared in its manifest's <activity> tag. By doing so, other applicationswill need to declare a corresponding <uses-permission> element in their own manifest to beable to start that activity.

See the Security and Permissions document for more information onpermissions and security in general.

Process Lifecycle

The Android system attempts to keepapplication process around for as long as possible, but eventually will need toremove old processes when memory runs low. As described in Activity Lifecycle, the decision about which process toremove is intimately tied to the state of the user's interaction with it. Ingeneral, there are four states a process can be in based on the activitiesrunning in it, listed here in order of importance. The system will kill lessimportant processes (the last ones) before it resorts to killing more importantprocesses (the first ones).

1.     The foreground activity (theactivity 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 lastresort, if it uses more memory than is available on the device. Generally atthis point the device has reached a memory paging state, so this is required inorder to keep the user interface responsive.

2.     A visible activity (an activitythat is visible to the user but not in the foreground, such as one sittingbehind a foreground dialog) is considered extremely important and will not bekilled unless that is required to keep the foreground activity running.

3.     A background activity (anactivity that is not visible to the user and has been paused) is no longercritical, so the system may safely kill its process to reclaim memory for otherforeground or visible processes. If its process needs to be killed, when theuser navigates back to the activity (making it visible on the screen again),its onCreate(Bundle) method will be called with thesavedInstanceState it had previously supplied in onSaveInstanceState(Bundle) so that it can restart itself in thesame state as the user last left it.

4.     An empty process is one hostingno activities or other application components (such as Service or BroadcastReceiver classes). These are killed very quicklyby the system as memory becomes low. For this reason, any background operationyou do outside of an activity must be executed in the context of an activityBroadcastReceiver or Service to ensure that the system knows it needs to keepyour process around.

Sometimes an Activity may need to do along-running operation that exists independently of the activity lifecycleitself. An example may be a camera application that allows you to upload apicture to a web site. The upload may take a long time, and the applicationshould allow the user to leave the application will it is executing. Toaccomplish this, your Activity should start a Service in which the upload takes place. Thisallows the system to properly prioritize your process (considering it to bemore important than other non-visible applications) for the duration of theupload, independent of whether the original activity is paused, stopped, orfinished.

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

http://developer.android.com/assets/images/triangle-closed.pngFrom class android.content.Context

String

ACCESSIBILITY_SERVICE

Use with getSystemService(String) to retrieve a AccessibilityManager for giving the user feedback for UI events through the registered event listeners.

String

ACCOUNT_SERVICE

Use with getSystemService(String) to retrieve a AccountManager for receiving intents at a time of your choosing.

String

ACTIVITY_SERVICE

Use with getSystemService(String) to retrieve a ActivityManager for interacting with the global system state.

String

ALARM_SERVICE

Use with getSystemService(String) to retrieve a AlarmManager for receiving intents at a time of your choosing.

String

AUDIO_SERVICE

Use with getSystemService(String) to retrieve a AudioManager for handling management of volume, ringer modes and audio routing.

int

BIND_AUTO_CREATE

Flag for bindService(Intent, ServiceConnection, int): automatically create the service as long as the binding exists.

int

BIND_DEBUG_UNBIND

Flag for bindService(Intent, ServiceConnection, int): include debugging help for mismatched calls to unbind.

int

BIND_NOT_FOREGROUND

Flag for bindService(Intent, ServiceConnection, int): don't allow this binding to raise the target service's process to the foreground scheduling priority.

String

CLIPBOARD_SERVICE

Use with getSystemService(String) to retrieve a ClipboardManager for accessing and modifying the contents of the global clipboard.

String

CONNECTIVITY_SERVICE

Use with getSystemService(String) to retrieve a ConnectivityManager for handling management of network connections.

int

CONTEXT_IGNORE_SECURITY

Flag for use with createPackageContext(String, int): ignore any security restrictions on the Context being requested, allowing it to always be loaded.

int

CONTEXT_INCLUDE_CODE

Flag for use with createPackageContext(String, int): include the application code with the context.

int

CONTEXT_RESTRICTED

Flag for use with createPackageContext(String, int): a restricted context may disable specific features.

String

DEVICE_POLICY_SERVICE

Use with getSystemService(String) to retrieve a DevicePolicyManager for working with global device policy management.

String

DOWNLOAD_SERVICE

Use with getSystemService(String) to retrieve a DownloadManager for requesting HTTP downloads.

String

DROPBOX_SERVICE

Use with getSystemService(String) to retrieve a DropBoxManager instance for recording diagnostic logs.

String

INPUT_METHOD_SERVICE

Use with getSystemService(String) to retrieve a InputMethodManager for accessing input methods.

String

KEYGUARD_SERVICE

Use with getSystemService(String) to retrieve a NotificationManager for controlling keyguard.

String

LAYOUT_INFLATER_SERVICE

Use with getSystemService(String) to retrieve a LayoutInflater for inflating layout resources in this context.

String

LOCATION_SERVICE

Use with getSystemService(String) to retrieve a LocationManager for controlling location updates.

int

MODE_APPEND

File creation mode: for use with openFileOutput(String, int), if the file already exists then write data to the end of the existing file instead of erasing it.

int

MODE_MULTI_PROCESS

SharedPreference loading flag: when set, the file on disk will be checked for modification even if the shared preferences instance is already loaded in this process.

int

MODE_PRIVATE

File creation mode: the default mode, where the created file can only be accessed by the calling application (or all applications sharing the same user ID).

int

MODE_WORLD_READABLE

File creation mode: allow all other applications to have read access to the created file.

int

MODE_WORLD_WRITEABLE

File creation mode: allow all other applications to have write access to the created file.

String

NFC_SERVICE

Use with getSystemService(String) to retrieve a NfcManager for using NFC.

String

NOTIFICATION_SERVICE

Use with getSystemService(String) to retrieve a NotificationManager for informing the user of background events.

String

POWER_SERVICE

Use with getSystemService(String) to retrieve a PowerManager for controlling power management, including "wake locks," which let you keep the device on while you're running long tasks.

String

SEARCH_SERVICE

Use with getSystemService(String) to retrieve a SearchManager for handling searches.

String

SENSOR_SERVICE

Use with getSystemService(String) to retrieve a SensorManager for accessing sensors.

String

STORAGE_SERVICE

Use with getSystemService(String) to retrieve a StorageManager for accessing system storage functions.

String

TELEPHONY_SERVICE

Use with getSystemService(String) to retrieve a TelephonyManager for handling management the telephony features of the device.

String

UI_MODE_SERVICE

Use with getSystemService(String) to retrieve a UiModeManager for controlling UI modes.

String

VIBRATOR_SERVICE

Use with getSystemService(String) to retrieve a Vibrator for interacting with the vibration hardware.

String

WALLPAPER_SERVICE

Use with getSystemService(String) to retrieve a com.android.server.WallpaperService for accessing wallpapers.

String

WIFI_SERVICE

Use with getSystemService(String) to retrieve a WifiManager for handling management of Wi-Fi access.

String

WINDOW_SERVICE

Use with getSystemService(String) to retrieve a WindowManager for accessing the system's window manager.

 

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)

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

          

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

Retrieve the non-configuration instance data that was previously returned by onRetainNonConfigurationInstance().

          

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.

          

int

getWallpaperDesiredMinimumHeight()

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

          

int

getWallpaperDesiredMinimumWidth()

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

          

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

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

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

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)

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)

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)

Show a dialog managed by this activity.

          

final void

showDialog(int id)

Simple version of showDialog(int, Bundle) that does not take any arguments.

          

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)

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

          

void

startManagingCursor(Cursor c)

This method is deprecated. Use CursorLoader instead.

          

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 CursorLoader instead.

          

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)

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)

This method is deprecated. Old no-arguments version of onPrepareDialog(int, Dialog, Bundle).

          

void

onPrepareDialog(int id, Dialog dialog, Bundle args)

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

          

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

http://developer.android.com/assets/images/triangle-closed.pngFrom class android.view.ContextThemeWrapper

void

attachBaseContext(Context newBase)

Set the base context for this ContextWrapper.

Object

getSystemService(String name)

Return the handle to a system-level service by name.

Resources.Theme

getTheme()

Return the Theme object associated with this Context.

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

setTheme(int resid)

Set the base theme for this context.

http://developer.android.com/assets/images/triangle-closed.pngFrom class android.content.ContextWrapper

void

attachBaseContext(Context base)

Set the base context for this ContextWrapper.

boolean

bindService(Intent service, ServiceConnection conn, int flags)

Connect to an application service, creating it if needed.

int

checkCallingOrSelfPermission(String permission)

Determine whether the calling process of an IPC or you have been granted a particular permission.

int

checkCallingOrSelfUriPermission(Uri uri, int modeFlags)

Determine whether the calling process of an IPC or you has been granted permission to access a specific URI.

int

checkCallingPermission(String permission)

Determine whether the calling process of an IPC you are handling has been granted a particular permission.

int

checkCallingUriPermission(Uri uri, int modeFlags)

Determine whether the calling process and user ID has been granted permission to access a specific URI.

int

checkPermission(String permission, int pid, int uid)

Determine whether the given permission is allowed for a particular process and user ID running in the system.

int

checkUriPermission(Uri uri, int pid, int uid, int modeFlags)

Determine whether a particular process and user ID has been granted permission to access a specific URI.

int

checkUriPermission(Uri uri, String readPermission, String writePermission, int pid, int uid, int modeFlags)

Check both a Uri and normal permission.

void

clearWallpaper()

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

Context

createPackageContext(String packageName, int flags)

Return a new Context object for the given application name.

String[]

databaseList()

Returns an array of strings naming the private databases associated with this Context's application package.

boolean

deleteDatabase(String name)

Delete an existing private SQLiteDatabase associated with this Context's application package.

boolean

deleteFile(String name)

Delete the given private file associated with this Context's application package.

void

enforceCallingOrSelfPermission(String permission, String message)

If neither you nor the calling process of an IPC you are handling has been granted a particular permission, throw a SecurityException.

void

enforceCallingOrSelfUriPermission(Uri uri, int modeFlags, String message)

If the calling process of an IPC or you has not been granted permission to access a specific URI, throw SecurityException.

void

enforceCallingPermission(String permission, String message)

If the calling process of an IPC you are handling has not been granted a particular permission, throw a SecurityException.

void

enforceCallingUriPermission(Uri uri, int modeFlags, String message)

If the calling process and user ID has not been granted permission to access a specific URI, throw SecurityException.

void

enforcePermission(String permission, int pid, int uid, String message)

If the given permission is not allowed for a particular process and user ID running in the system, throw a SecurityException.

void

enforceUriPermission(Uri uri, int pid, int uid, int modeFlags, String message)

If a particular process and user ID has not been granted permission to access a specific URI, throw SecurityException.

void

enforceUriPermission(Uri uri, String readPermission, String writePermission, int pid, int uid, int modeFlags, String message)

Enforce both a Uri and normal permission.

String[]

fileList()

Returns an array of strings naming the private files associated with this Context's application package.

Context

getApplicationContext()

Return the context of the single, global Application object of the current process.

ApplicationInfo

getApplicationInfo()

Return the full application info for this context's package.

AssetManager

getAssets()

Return an AssetManager instance for your application's package.

Context

getBaseContext()

File

getCacheDir()

Returns the absolute path to the application specific cache directory on the filesystem.

ClassLoader

getClassLoader()

Return a class loader you can use to retrieve classes in this package.

ContentResolver

getContentResolver()

Return a ContentResolver instance for your application's package.

File

getDatabasePath(String name)

Returns the absolute path on the filesystem where a database created with openOrCreateDatabase(String, int, SQLiteDatabase.CursorFactory) is stored.

File

getDir(String name, int mode)

Retrieve, creating if needed, a new directory in which the application can place its own custom data files.

File

getExternalCacheDir()

Returns the absolute path to the directory on the external filesystem (that is somewhere on Environment.getExternalStorageDirectory() where the application can place cache files it owns.

File

getExternalFilesDir(String type)

Returns the absolute path to the directory on the external filesystem (that is somewhere on Environment.getExternalStorageDirectory()) where the application can place persistent files it owns.

File

getFileStreamPath(String name)

Returns the absolute path on the filesystem where a file created with openFileOutput(String, int) is stored.

File

getFilesDir()

Returns the absolute path to the directory on the filesystem where files created with openFileOutput(String, int) are stored.

Looper

getMainLooper()

Return the Looper for the main thread of the current process.

File

getObbDir()

Return the directory where this application's OBB files (if there are any) can be found.

String

getPackageCodePath()

Return the full path to this context's primary Android package.

PackageManager

getPackageManager()

Return PackageManager instance to find global package information.

String

getPackageName()

Return the name of this application's package.

String

getPackageResourcePath()

Return the full path to this context's primary Android package.

Resources

getResources()

Return a Resources instance for your application's package.

SharedPreferences

getSharedPreferences(String name, int mode)

Retrieve and hold the contents of the preferences file 'name', returning a SharedPreferences through which you can retrieve and modify its values.

Object

getSystemService(String name)

Return the handle to a system-level service by name.

Resources.Theme

getTheme()

Return the Theme object associated with this Context.

Drawable

getWallpaper()

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

int

getWallpaperDesiredMinimumHeight()

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

int

getWallpaperDesiredMinimumWidth()

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

void

grantUriPermission(String toPackage, Uri uri, int modeFlags)

Grant permission to access a specific Uri to another package, regardless of whether that package has general permission to access the Uri's content provider.

boolean

isRestricted()

Indicates whether this Context is restricted.

FileInputStream

openFileInput(String name)

Open a private file associated with this Context's application package for reading.

FileOutputStream

openFileOutput(String name, int mode)

Open a private file associated with this Context's application package for writing.

SQLiteDatabase

openOrCreateDatabase(String name, int mode, SQLiteDatabase.CursorFactory factory)

Open a new private SQLiteDatabase associated with this Context's application package.

SQLiteDatabase

openOrCreateDatabase(String name, int mode, SQLiteDatabase.CursorFactory factory, DatabaseErrorHandler errorHandler)

Open a new private SQLiteDatabase associated with this Context's application package.

Drawable

peekWallpaper()

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

Intent

registerReceiver(BroadcastReceiver receiver, IntentFilter filter)

Register a BroadcastReceiver to be run in the main activity thread.

Intent

registerReceiver(BroadcastReceiver receiver, IntentFilter filter, String broadcastPermission, Handler scheduler)

Register to receive intent broadcasts, to run in the context of scheduler.

void

removeStickyBroadcast(Intent intent)

Remove the data previously sent with sendStickyBroadcast(Intent), so that it is as if the sticky broadcast had never happened.

void

revokeUriPermission(Uri uri, int modeFlags)

Remove all permissions to access a particular content provider Uri that were previously added with grantUriPermission(String, Uri, int).

void

sendBroadcast(Intent intent)

Broadcast the given intent to all interested BroadcastReceivers.

void

sendBroadcast(Intent intent, String receiverPermission)

Broadcast the given intent to all interested BroadcastReceivers, allowing an optional required permission to be enforced.

void

sendOrderedBroadcast(Intent intent, String receiverPermission, BroadcastReceiver resultReceiver, Handler scheduler, int initialCode, String initialData, Bundle initialExtras)

Version of sendBroadcast(Intent) that allows you to receive data back from the broadcast.

void

sendOrderedBroadcast(Intent intent, String receiverPermission)

Broadcast the given intent to all interested BroadcastReceivers, delivering them one at a time to allow more preferred receivers to consume the broadcast before it is delivered to less preferred receivers.

void

sendStickyBroadcast(Intent intent)

Perform a sendBroadcast(Intent) that is "sticky," meaning the Intent you are sending stays around after the broadcast is complete, so that others can quickly retrieve that data through the return value of registerReceiver(BroadcastReceiver, IntentFilter).

void

sendStickyOrderedBroadcast(Intent intent, BroadcastReceiver resultReceiver, Handler scheduler, int initialCode, String initialData, Bundle initialExtras)

Version of sendStickyBroadcast(Intent) that allows you to receive data back from the broadcast.

void

setTheme(int resid)

Set the base theme for this context.

void

setWallpaper(Bitmap bitmap)

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

void

setWallpaper(InputStream data)

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

void

startActivities(Intent[] intents)

Launch multiple new activities.

void

startActivity(Intent intent)

Launch a new activity.

boolean

startInstrumentation(ComponentName className, String profileFile, Bundle arguments)

Start executing an Instrumentation class.

void

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

Like startActivity(Intent), but taking a IntentSender to start.

ComponentName

startService(Intent service)

Request that a given application service be started.

boolean

stopService(Intent name)

Request that a given application service be stopped.

void

unbindService(ServiceConnection conn)

Disconnect from an application service.

void

unregisterReceiver(BroadcastReceiver receiver)

Unregister a previously registered BroadcastReceiver.

http://developer.android.com/assets/images/triangle-closed.pngFrom class android.content.Context

abstract boolean

bindService(Intent service, ServiceConnection conn, int flags)

Connect to an application service, creating it if needed.

abstract int

checkCallingOrSelfPermission(String permission)

Determine whether the calling process of an IPC or you have been granted a particular permission.

abstract int

checkCallingOrSelfUriPermission(Uri uri, int modeFlags)

Determine whether the calling process of an IPC or you has been granted permission to access a specific URI.

abstract int

checkCallingPermission(String permission)

Determine whether the calling process of an IPC you are handling has been granted a particular permission.

abstract int

checkCallingUriPermission(Uri uri, int modeFlags)

Determine whether the calling process and user ID has been granted permission to access a specific URI.

abstract int

checkPermission(String permission, int pid, int uid)

Determine whether the given permission is allowed for a particular process and user ID running in the system.

abstract int

checkUriPermission(Uri uri, int pid, int uid, int modeFlags)

Determine whether a particular process and user ID has been granted permission to access a specific URI.

abstract int

checkUriPermission(Uri uri, String readPermission, String writePermission, int pid, int uid, int modeFlags)

Check both a Uri and normal permission.

abstract void

clearWallpaper()

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

abstract Context

createPackageContext(String packageName, int flags)

Return a new Context object for the given application name.

abstract String[]

databaseList()

Returns an array of strings naming the private databases associated with this Context's application package.

abstract boolean

deleteDatabase(String name)

Delete an existing private SQLiteDatabase associated with this Context's application package.

abstract boolean

deleteFile(String name)

Delete the given private file associated with this Context's application package.

abstract void

enforceCallingOrSelfPermission(String permission, String message)

If neither you nor the calling process of an IPC you are handling has been granted a particular permission, throw a SecurityException.

abstract void

enforceCallingOrSelfUriPermission(Uri uri, int modeFlags, String message)

If the calling process of an IPC or you has not been granted permission to access a specific URI, throw SecurityException.

abstract void

enforceCallingPermission(String permission, String message)

If the calling process of an IPC you are handling has not been granted a particular permission, throw a SecurityException.

abstract void

enforceCallingUriPermission(Uri uri, int modeFlags, String message)

If the calling process and user ID has not been granted permission to access a specific URI, throw SecurityException.

abstract void

enforcePermission(String permission, int pid, int uid, String message)

If the given permission is not allowed for a particular process and user ID running in the system, throw a SecurityException.

abstract void

enforceUriPermission(Uri uri, int pid, int uid, int modeFlags, String message)

If a particular process and user ID has not been granted permission to access a specific URI, throw SecurityException.

abstract void

enforceUriPermission(Uri uri, String readPermission, String writePermission, int pid, int uid, int modeFlags, String message)

Enforce both a Uri and normal permission.

abstract String[]

fileList()

Returns an array of strings naming the private files associated with this Context's application package.

abstract Context

getApplicationContext()

Return the context of the single, global Application object of the current process.

abstract ApplicationInfo

getApplicationInfo()

Return the full application info for this context's package.

abstract AssetManager

getAssets()

Return an AssetManager instance for your application's package.

abstract File

getCacheDir()

Returns the absolute path to the application specific cache directory on the filesystem.

abstract ClassLoader

getClassLoader()

Return a class loader you can use to retrieve classes in this package.

abstract ContentResolver

getContentResolver()

Return a ContentResolver instance for your application's package.

abstract File

getDatabasePath(String name)

Returns the absolute path on the filesystem where a database created with openOrCreateDatabase(String, int, SQLiteDatabase.CursorFactory) is stored.

abstract File

getDir(String name, int mode)

Retrieve, creating if needed, a new directory in which the application can place its own custom data files.

abstract File

getExternalCacheDir()

Returns the absolute path to the directory on the external filesystem (that is somewhere on Environment.getExternalStorageDirectory() where the application can place cache files it owns.

abstract File

getExternalFilesDir(String type)

Returns the absolute path to the directory on the external filesystem (that is somewhere on Environment.getExternalStorageDirectory()) where the application can place persistent files it owns.

abstract File

getFileStreamPath(String name)

Returns the absolute path on the filesystem where a file created with openFileOutput(String, int) is stored.

abstract File

getFilesDir()

Returns the absolute path to the directory on the filesystem where files created with openFileOutput(String, int) are stored.

abstract Looper

getMainLooper()

Return the Looper for the main thread of the current process.

abstract File

getObbDir()

Return the directory where this application's OBB files (if there are any) can be found.

abstract String

getPackageCodePath()

Return the full path to this context's primary Android package.

abstract PackageManager

getPackageManager()

Return PackageManager instance to find global package information.

abstract String

getPackageName()

Return the name of this application's package.

abstract String

getPackageResourcePath()

Return the full path to this context's primary Android package.

abstract Resources

getResources()

Return a Resources instance for your application's package.

abstract SharedPreferences

getSharedPreferences(String name, int mode)

Retrieve and hold the contents of the preferences file 'name', returning a SharedPreferences through which you can retrieve and modify its values.

final String

getString(int resId)

Return a localized string from the application's package's default string table.

final String

getString(int resId, Object... formatArgs)

Return a localized formatted string from the application's package's default string table, substituting the format arguments as defined in Formatter and format(String, Object...).

abstract Object

getSystemService(String name)

Return the handle to a system-level service by name.

final CharSequence

getText(int resId)

Return a localized, styled CharSequence from the application's package's default string table.

abstract Resources.Theme

getTheme()

Return the Theme object associated with this Context.

abstract Drawable

getWallpaper()

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

abstract int

getWallpaperDesiredMinimumHeight()

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

abstract int

getWallpaperDesiredMinimumWidth()

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

abstract void

grantUriPermission(String toPackage, Uri uri, int modeFlags)

Grant permission to access a specific Uri to another package, regardless of whether that package has general permission to access the Uri's content provider.

boolean

isRestricted()

Indicates whether this Context is restricted.

final TypedArray

obtainStyledAttributes(int[] attrs)

Retrieve styled attribute information in this Context's theme.

final TypedArray

obtainStyledAttributes(AttributeSet set, int[] attrs)

Retrieve styled attribute information in this Context's theme.

final TypedArray

obtainStyledAttributes(int resid, int[] attrs)

Retrieve styled attribute information in this Context's theme.

final TypedArray

obtainStyledAttributes(AttributeSet set, int[] attrs, int defStyleAttr, int defStyleRes)

Retrieve styled attribute information in this Context's theme.

abstract FileInputStream

openFileInput(String name)

Open a private file associated with this Context's application package for reading.

abstract FileOutputStream

openFileOutput(String name, int mode)

Open a private file associated with this Context's application package for writing.

abstract SQLiteDatabase

openOrCreateDatabase(String name, int mode, SQLiteDatabase.CursorFactory factory)

Open a new private SQLiteDatabase associated with this Context's application package.

abstract SQLiteDatabase

openOrCreateDatabase(String name, int mode, SQLiteDatabase.CursorFactory factory, DatabaseErrorHandler errorHandler)

Open a new private SQLiteDatabase associated with this Context's application package.

abstract Drawable

peekWallpaper()

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

abstract Intent

registerReceiver(BroadcastReceiver receiver, IntentFilter filter)

Register a BroadcastReceiver to be run in the main activity thread.

abstract Intent

registerReceiver(BroadcastReceiver receiver, IntentFilter filter, String broadcastPermission, Handler scheduler)

Register to receive intent broadcasts, to run in the context of scheduler.

abstract void

removeStickyBroadcast(Intent intent)

Remove the data previously sent with sendStickyBroadcast(Intent), so that it is as if the sticky broadcast had never happened.

abstract void

revokeUriPermission(Uri uri, int modeFlags)

Remove all permissions to access a particular content provider Uri that were previously added with grantUriPermission(String, Uri, int).

abstract void

sendBroadcast(Intent intent)

Broadcast the given intent to all interested BroadcastReceivers.

abstract void

sendBroadcast(Intent intent, String receiverPermission)

Broadcast the given intent to all interested BroadcastReceivers, allowing an optional required permission to be enforced.

abstract void

sendOrderedBroadcast(Intent intent, String receiverPermission, BroadcastReceiver resultReceiver, Handler scheduler, int initialCode, String initialData, Bundle initialExtras)

Version of sendBroadcast(Intent) that allows you to receive data back from the broadcast.

abstract void

sendOrderedBroadcast(Intent intent, String receiverPermission)

Broadcast the given intent to all interested BroadcastReceivers, delivering them one at a time to allow more preferred receivers to consume the broadcast before it is delivered to less preferred receivers.

abstract void

sendStickyBroadcast(Intent intent)

Perform a sendBroadcast(Intent) that is "sticky," meaning the Intent you are sending stays around after the broadcast is complete, so that others can quickly retrieve that data through the return value of registerReceiver(BroadcastReceiver, IntentFilter).

abstract void

sendStickyOrderedBroadcast(Intent intent, BroadcastReceiver resultReceiver, Handler scheduler, int initialCode, String initialData, Bundle initialExtras)

Version of sendStickyBroadcast(Intent) that allows you to receive data back from the broadcast.

abstract void

setTheme(int resid)

Set the base theme for this context.

abstract void

setWallpaper(Bitmap bitmap)

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

abstract void

setWallpaper(InputStream data)

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

abstract void

startActivities(Intent[] intents)

Launch multiple new activities.

abstract void

startActivity(Intent intent)

Launch a new activity.

abstract boolean

startInstrumentation(ComponentName className, String profileFile, Bundle arguments)

Start executing an Instrumentation class.

abstract void

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

Like startActivity(Intent), but taking a IntentSender to start.

abstract ComponentName

startService(Intent service)

Request that a given application service be started.

abstract boolean

stopService(Intent service)

Request that a given application service be stopped.

abstract void

unbindService(ServiceConnection conn)

Disconnect from an application service.

abstract void

unregisterReceiver(BroadcastReceiver receiver)

Unregister a previously registered BroadcastReceiver.

http://developer.android.com/assets/images/triangle-closed.pngFrom class java.lang.Object

Object

clone()

Creates and returns a copy of this Object.

boolean

equals(Object o)

Compares this instance with the specified object and indicates if they are equal.

void

finalize()

Called before the object's memory is reclaimed by the VM.

final Class<?>

getClass()

Returns the unique instance of Class that represents this object's class.

int

hashCode()

Returns an integer hash code for this object.

final void

notify()

Causes a thread which is waiting on this object's monitor (by means of calling one of the wait() methods) to be woken up.

final void

notifyAll()

Causes all threads which are waiting on this object's monitor (by means of calling one of the wait() methods) to be woken up.

String

toString()

Returns a string containing a concise, human-readable description of this object.

final void

wait()

Causes the calling thread to wait until another thread calls the notify() or notifyAll() method of this object.

final void

wait(long millis, int nanos)

Causes the calling thread to wait until another thread calls the notify() or notifyAll() method of this object or until the specified timeout expires.

final void

wait(long millis)

Causes the calling thread to wait until another thread calls the notify() or notifyAll() method of this object or until the specified timeout expires.

http://developer.android.com/assets/images/triangle-closed.pngFrom interface android.content.ComponentCallbacks

abstract void

onConfigurationChanged(Configuration newConfig)

Called by the system when the device configuration changes while your component is running.

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

http://developer.android.com/assets/images/triangle-closed.pngFrom interface android.view.KeyEvent.Callback

abstract boolean

onKeyDown(int keyCode, KeyEvent event)

Called when a key down event has occurred.

abstract boolean

onKeyLongPress(int keyCode, KeyEvent event)

Called when a long press has occurred.

abstract boolean

onKeyMultiple(int keyCode, int count, KeyEvent event)

Called when multiple down/up pairs of the same key have occurred in a row.

abstract boolean

onKeyUp(int keyCode, KeyEvent event)

Called when a key up event has occurred.

http://developer.android.com/assets/images/triangle-closed.pngFrom interface android.view.LayoutInflater.Factory

abstract View

onCreateView(String name, Context context, AttributeSet attrs)

Hook you can supply that is called when inflating from a LayoutInflater.

http://developer.android.com/assets/images/triangle-closed.pngFrom interface android.view.LayoutInflater.Factory2

abstract View

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

Version of onCreateView(String, Context, AttributeSet) that also supplies the parent that the view created view will be placed in.

http://developer.android.com/assets/images/triangle-closed.pngFrom interface android.view.View.OnCreateContextMenuListener

abstract void

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

Called when the context menu for this view is being built.

http://developer.android.com/assets/images/triangle-closed.pngFrom interface android.view.Window.Callback

abstract boolean

dispatchKeyEvent(KeyEvent event)

Called to process key events.

abstract boolean

dispatchKeyShortcutEvent(KeyEvent event)

Called to process a key shortcut event.

abstract boolean

dispatchPopulateAccessibilityEvent(AccessibilityEvent event)

Called to process population of AccessibilityEvents.

abstract boolean

dispatchTouchEvent(MotionEvent event)

Called to process touch screen events.

abstract boolean

dispatchTrackballEvent(MotionEvent event)

Called to process trackball events.

abstract void

onActionModeFinished(ActionMode mode)

Called when an action mode has been finished.

abstract void

onActionModeStarted(ActionMode mode)

Called when an action mode has been started.

abstract void

onAttachedToWindow()

Called when the window has been attached to the window manager.

abstract void

onContentChanged()

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

abstract boolean

onCreatePanelMenu(int featureId, Menu menu)

Initialize the contents of the menu for panel 'featureId'.

abstract View

onCreatePanelView(int featureId)

Instantiate the view to display in the panel for 'featureId'.

abstract void

onDetachedFromWindow()

Called when the window has been attached to the window manager.

abstract boolean

onMenuItemSelected(int featureId, MenuItem item)

Called when a panel's menu item has been selected by the user.

abstract boolean

onMenuOpened(int featureId, Menu menu)

Called when a panel's menu is opened by the user.

abstract void

onPanelClosed(int featureId, Menu menu)

Called when a panel is being closed.

abstract boolean

onPreparePanel(int featureId, View view, Menu menu)

Prepare a panel to be displayed.

abstract boolean

onSearchRequested()

Called when the user signals the desire to start a search.

abstract void

onWindowAttributesChanged(WindowManager.LayoutParams attrs)

This is called whenever the current window attributes change.

abstract void

onWindowFocusChanged(boolean hasFocus)

This hook is called whenever the window focus changes.

abstract ActionMode

onWindowStartingActionMode(ActionMode.Callback callback)

Called when an action mode is being started for this window.

Constants

public staticfinal int DEFAULT_KEYS_DIALER

Since: APILevel 1

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

See Also

·        setDefaultKeyMode(int)

Constant Value: 1 (0x00000001)

public staticfinal int DEFAULT_KEYS_DISABLE

Since: APILevel 1

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

See Also

·        setDefaultKeyMode(int)

Constant Value: 0 (0x00000000)

public staticfinal int DEFAULT_KEYS_SEARCH_GLOBAL

Since: APILevel 1

Use with setDefaultKeyMode(int) to specify that unhandled keystrokeswill start a global search (typically web search, but some platforms may definealternate methods for global search)

See android.app.SearchManager for more details.

See Also

·        setDefaultKeyMode(int)

Constant Value: 4 (0x00000004)

public staticfinal int DEFAULT_KEYS_SEARCH_LOCAL

Since: APILevel 1

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

See android.app.SearchManager for more details.

See Also

·        setDefaultKeyMode(int)

Constant Value: 3 (0x00000003)

public staticfinal int DEFAULT_KEYS_SHORTCUT

Since: APILevel 1

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

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

See Also

·        setDefaultKeyMode(int)

Constant Value: 2 (0x00000002)

public staticfinal int RESULT_CANCELED

Since: APILevel 1

Standard activity result: operationcanceled.

Constant Value: 0 (0x00000000)

public staticfinal int RESULT_FIRST_USER

Since: APILevel 1

Start of user-defined activity results.

Constant Value: 1 (0x00000001)

public staticfinal int RESULT_OK

Since: APILevel 1

Standard activity result: operationsucceeded.

Constant Value: -1 (0xffffffff)

Fields

protected staticfinal int[] FOCUSED_STATE_SET

Since: APILevel 1

Public Constructors

public Activity ()

Since: APILevel 1

Public Methods

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

Since: APILevel 1

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

Parameters

view

The desired content to display.

params

Layout parameters for the view.

public void closeContextMenu ()

Since: APILevel 3

Programmatically closes the most recently opened contextmenu, if showing.

public void closeOptionsMenu ()

Since: APILevel 1

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

public PendingIntent createPendingResult (intrequestCode, Intent data, intflags)

Since: APILevel 1

Create a new PendingIntent object whichyou 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 invalidafter a result is sent back) or multiple (allowing any number of results to besent 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 thegiven parameters. May return null only if PendingIntent.FLAG_NO_CREATE has been supplied.

See Also

·        PendingIntent

public finalvoid dismissDialog (int id)

Since: APILevel 1

Dismiss a dialog that was previouslyshown via showDialog(int).

Parameters

id

The id of the managed dialog.

Throws

IllegalArgumentException

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

See Also

·        onCreateDialog(int, Bundle)

·        onPrepareDialog(int, Dialog,Bundle)

·        showDialog(int)

·        removeDialog(int)

public boolean dispatchKeyEvent (KeyEvent event)

Since: APILevel 1

Called to process key events. You canoverride this to intercept all key events before they are dispatched to thewindow. Be sure to call this implementation for key events that should behandled normally.

Parameters

event

The key event.

Returns

·        boolean Return true if this event was consumed.

public boolean dispatchKeyShortcutEvent (KeyEvent event)

Since: APILevel 11

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

Parameters

event

The key shortcut event.

Returns

·        True if this event was consumed.

public boolean dispatchPopulateAccessibilityEvent (AccessibilityEvent event)

Since: APILevel 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: APILevel 1

Called to process touch screen events.You can override this to intercept all touch screen events before they aredispatched to the window. Be sure to call this implementation for touch screenevents 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: APILevel 1

Called to process trackball events. Youcan override this to intercept all trackball events before they are dispatchedto the window. Be sure to call this implementation for trackball events thatshould 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: APILevel 11

Print the Activity's state into thegiven 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: APILevel 1

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

Returns

·        The view if found or null otherwise.

public void finish ()

Since: APILevel 1

Call this when your activity is done and should beclosed. The ActivityResult is propagated back to whoever launched you viaonActivityResult().

public void finishActivity (intrequestCode)

Since: APILevel 1

Force finish another activity that youhad 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, intrequestCode)

Since: APILevel 1

This is called when a child activity ofthis 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: APILevel 1

This is called when a child activity ofthis one calls its finish() method. The default implementationsimply calls finish() on this activity (the parent), finishing the entiregroup.

Parameters

child

The activity making the call.

See Also

·        finish()

public ActionBar getActionBar ()

Since: APILevel 11

Retrieve a reference to this activity's ActionBar.

Returns

·        The Activity's ActionBar, or null if it does not haveone.

public final Application getApplication ()

Since: APILevel 1

Return the application that owns this activity.

public ComponentName getCallingActivity ()

Since: APILevel 1

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

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

Returns

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

public String getCallingPackage ()

Since: APILevel 1

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

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

Returns

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

public int getChangingConfigurations ()

Since: APILevel 1

If this activity is being destroyedbecause it can not handle a configuration parameter being changed (and thus itsonConfigurationChanged(Configuration) method is not being called), then you can use thismethod to discover the set of changes that have occurred while in the processof 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 asan optimization hint.

Returns

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

public ComponentName getComponentName ()

Since: APILevel 1

Returns complete component name of thisactivity.

Returns

·        Returns the complete component name for this activity

public View getCurrentFocus ()

Since: APILevel 1

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

Returns

·        View The current View with focus or null.

See Also

·        getWindow()

·        getCurrentFocus()

public FragmentManager getFragmentManager ()

Since: APILevel 11

Return the FragmentManager for interacting with fragmentsassociated with this activity.

public Intent getIntent ()

Since: APILevel 1

Return the intent that started this activity.

public Object getLastNonConfigurationInstance ()

Since: APILevel 1

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

Note that the data you retrieve hereshould only be used as an optimization for handling configurationchanges. You should always be able to handle getting a null pointer back, andan activity must still be able to restore itself to its previous state (throughthe normal onSaveInstanceState(Bundle) mechanism) even if this functionreturns null.

Returns

·        Returns the object previously returned by onRetainNonConfigurationInstance().

public LayoutInflater getLayoutInflater ()

Since: APILevel 1

Convenience for calling getLayoutInflater().

public LoaderManager getLoaderManager ()

Since: APILevel 11

Return the LoaderManager for this fragment, creating itif needed.

public String getLocalClassName ()

Since: APILevel 1

Returns class name for this activitywith the package prefix removed. This is the default name used to read andwrite settings.

Returns

·        The local class name.

public MenuInflater getMenuInflater ()

Since: APILevel 1

Returns a MenuInflater with this context.

public final Activity getParent ()

Since: APILevel 1

Return the parent activity if this view is an embeddedchild.

public SharedPreferences getPreferences (int mode)

Since: APILevel 1

Retrieve a SharedPreferences object for accessing preferences that areprivate to this activity. This simply calls the underlying getSharedPreferences(String, int) method by passing in this activity'sclass 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 beused to retrieve and modify the preference values.

public int getRequestedOrientation ()

Since: APILevel 1

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

Returns

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

public Object getSystemService (String name)

Since: APILevel 1

Return the handle to a system-levelservice 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 placecustom windows. The returned object is a WindowManager.

LAYOUT_INFLATER_SERVICE ("layout_inflater")

A LayoutInflater for inflating layout resources in thiscontext.

ACTIVITY_SERVICE ("activity")

A ActivityManager for interacting with the globalactivity state of the system.

POWER_SERVICE ("power")

A PowerManager for controlling power management.

ALARM_SERVICE ("alarm")

A AlarmManager for receiving intents at the time ofyour choosing.

NOTIFICATION_SERVICE ("notification")

A NotificationManager for informing the user of backgroundevents.

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

CONNECTIVITY_SERVICE ("connection")

A ConnectivityManager for handling management of networkconnections.

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 thisAPI 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: APILevel 1

Return the identifier of the task thisactivity is in. This identifier will remain the same for the lifetime of theactivity.

Returns

·        Task identifier, an opaque integer.

public final CharSequence getTitle ()

Since: APILevel 1

public final intgetTitleColor ()

Since: APILevel 1

public final intgetVolumeControlStream()

Since: APILevel 1

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

Returns

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

See Also

·        setVolumeControlStream(int)

public int getWallpaperDesiredMinimumHeight ()

Since: APILevel 1

This method isdeprecated.
Use
WallpaperManager.getDesiredMinimumHeight() instead.

public int getWallpaperDesiredMinimumWidth ()

Since: APILevel 1

This method isdeprecated.
Use
WallpaperManager.getDesiredMinimumWidth() instead.

public Window getWindow ()

Since: APILevel 1

Retrieve the current Window for the activity. This can be used todirectly access parts of the Window API that are not available throughActivity/Screen.

Returns

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

public WindowManager getWindowManager ()

Since: APILevel 1

Retrieve the window manager for showing custom windows.

public boolean hasWindowFocus ()

Since: APILevel 3

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

Returns

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

See Also

·        onWindowAttributesChanged(android.view.WindowManager.LayoutParams)

public void invalidateOptionsMenu ()

Since: APILevel 11

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

public boolean isChangingConfigurations ()

Since: APILevel 11

Check to see whether this activity is inthe process of being destroyed in order to be recreated with a newconfiguration. This is often used in onStop() to determine whether the state needs tobe 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 berecreated with a new configuration, returns true; else returns false.

public finalboolean isChild ()

Since: APILevel 1

Is this activity embedded inside of another activity?

public boolean isFinishing ()

Since: APILevel 1

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

Returns

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

See Also

·        finish()

public boolean isTaskRoot ()

Since: APILevel 1

Return whether this activity is the rootof 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: APILevel 1

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

Parameters

uri

The URI of the content provider to query.

projection

List of columns to return.

selection

SQL WHERE clause.

selectionArgs

The arguments to selection, if any ?s are pesent

sortOrder

SQL ORDER BY clause.

Returns

·        The Cursor that was returned by query().

See Also

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

·        startManagingCursor(Cursor)

public boolean moveTaskToBack (booleannonRoot)

Since: APILevel 1

Move the task containing this activityto the back of the activity stack. The activity's order within the task isunchanged.

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: APILevel 11

Notifies the activity that an actionmode has finished. Activity subclasses overriding this method should call thesuperclass implementation.

Parameters

mode

The action mode that just finished.

public void onActionModeStarted (ActionMode mode)

Since: APILevel 11

Notifies the Activity that an actionmode has been started. Activity subclasses overriding this method should callthe superclass implementation.

Parameters

mode

The new action mode.

public void onAttachFragment (Fragment fragment)

Since: APILevel 11

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

public void onAttachedToWindow ()

Since: APILevel 5

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

See Also

·        onAttachedToWindow()

public void onBackPressed ()

Since: APILevel 5

Called when the activity has detected the user's press ofthe 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: APILevel 1

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

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

Parameters

newConfig

The new device configuration.

public void onContentChanged ()

Since: APILevel 1

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

public boolean onContextItemSelected (MenuItem item)

Since: APILevel 1

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

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

Derived classes should call through tothe 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 menuprocessing to proceed, true to consume it here.

public void onContextMenuClosed (Menu menu)

Since: APILevel 1

This hook is called whenever the contextmenu is being closed (either by the user canceling the menu with the back/menubutton, 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: APILevel 1

Called when a context menu for the view is about to beshown. Unlike onCreateOptionsMenu(Menu), this will be called every time thecontext menu is about to be shown and should be populated for the view (or iteminside 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 contextmenu after this method returns. Called when the context menu for this view isbeing 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: APILevel 1

Generate a new description for thisactivity. This method is called before pausing the activity and can, ifdesired, return some textual description of its current state to be displayedto the user.

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

Returns

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

See Also

·        onCreateThumbnail(Bitmap, Canvas)

·        onSaveInstanceState(Bundle)

·        onPause()

public boolean onCreateOptionsMenu (Menu menu)

Since: APILevel 1

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

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

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

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

When you add items to the menu, you canimplement 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 youreturn false it will not be shown.

See Also

·        onPrepareOptionsMenu(Menu)

·        onOptionsItemSelected(MenuItem)

public boolean onCreatePanelMenu (int featureId, Menu menu)

Since: APILevel 1

Default implementation of onCreatePanelMenu(int, Menu) for activities. This calls through tothe new onCreateOptionsMenu(Menu) method for the FEATURE_OPTIONS_PANEL panel, so that subclasses of Activitydon'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 bedisplayed; if you return false it will not be shown.

public View onCreatePanelView (int featureId)

Since: APILevel 1

Default implementation of onCreatePanelView(int) for activities. This simply returnsnull 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: APILevel 1

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

The default implementation returns failsand does not draw a thumbnail; this will result in the platform creating itsown 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; otherwiseafter you return it will be filled with a default thumbnail.

See Also

·        onCreateDescription()

·        onSaveInstanceState(Bundle)

·        onPause()

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

Since: APILevel 11

Standard implementation of onCreateView(View, String,Context, AttributeSet) used when inflating with the LayoutInflater returned by getSystemService(String). This implementation handles tags toembed 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 defaultbehavior.

See Also

·        createView(String, String,AttributeSet)

·        getLayoutInflater()

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

Since: APILevel 1

Standard implementation of onCreateView(String, Context,AttributeSet) used when inflating with the LayoutInflater returned by getSystemService(String). This implementation does nothing andis 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 defaultbehavior.

See Also

·        createView(String, String,AttributeSet)

·        getLayoutInflater()

public void onDetachedFromWindow ()

Since: APILevel 5

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

See Also

·        onDetachedFromWindow()

public boolean onKeyDown (int keyCode, KeyEvent event)

Since: APILevel 1

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

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

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

Other additional default key handlingmay 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 beingpropagated further, or false to indicate that you have not handledthis event and it should continue to be propagated.

See Also

·        onKeyUp(int, KeyEvent)

·        KeyEvent

public boolean onKeyLongPress (int keyCode, KeyEvent event)

Since: APILevel 5

Default implementation of KeyEvent.Callback.onKeyLongPress(): always returns false (doesn't handlethe 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 toallow the event to be handled by the next receiver, return false.

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

Since: APILevel 1

Default implementation of KeyEvent.Callback.onKeyMultiple(): always returns false (doesn't handlethe 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 toallow the event to be handled by the next receiver, return false.

public boolean onKeyShortcut (int keyCode, KeyEvent event)

Since: APILevel 11

Called when a key shortcut event is nothandled by any of the views in the Activity. Override this method to implementglobal key shortcuts for the Activity. Key shortcuts can also be implemented bysetting 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: APILevel 1

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

The default implementation handlesKEYCODE_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 beingpropagated further, or false to indicate that you have not handledthis event and it should continue to be propagated.

See Also

·        onKeyDown(int, KeyEvent)

·        KeyEvent

public void onLowMemory ()

Since: APILevel 1

This is called when the overall systemis running low on memory, and would like actively running process to try totighten their belt. While the exact point at which this will be called is notdefined, generally it will happen around the time all background process havebeen killed, that is before reaching the point of killing processes hostingservice and foreground UI that we would like to avoid killing.

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

public boolean onMenuItemSelected (int featureId, MenuItem item)

Since: APILevel 1

Default implementation of onMenuItemSelected(int, MenuItem) for activities. This calls through tothe new onOptionsItemSelected(MenuItem) method for the FEATURE_OPTIONS_PANEL panel, so that subclasses of Activitydon'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, orfalse to perform the normal menu handling (calling its Runnable or sending aMessage to its target Handler).

public boolean onMenuOpened (int featureId, Menu menu)

Since: APILevel 1

Called when a panel's menu is opened bythe user. This may also be called when the menu is changing from one type toanother (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: APILevel 1

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

Derived classes should call through tothe 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 toproceed, true to consume it here.

See Also

·        onCreateOptionsMenu(Menu)

public void onOptionsMenuClosed (Menu menu)

Since: APILevel 1

This hook is called whenever the optionsmenu is being closed (either by the user canceling the menu with the back/menubutton, 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: APILevel 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 Activitydon'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: APILevel 1

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

The default implementation updates thesystem menu items based on the activity's state. Deriving classes should alwayscall 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 youreturn false it will not be shown.

See Also

·        onCreateOptionsMenu(Menu)

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

Since: APILevel 1

Default implementation of onPreparePanel(int, View, Menu) for activities. This calls through tothe new onPrepareOptionsMenu(Menu) method for the FEATURE_OPTIONS_PANEL panel, so that subclasses of Activitydon'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 bedisplayed; if you return false it will not be shown.

public Object onRetainNonConfigurationInstance ()

Since: APILevel 1

Called by the system, as part ofdestroying an activity due to a configuration change, when it is known that anew instance will immediately be created for the new configuration. You canreturn any object you like here, including the activity instance itself, whichcan later be retrieved by calling getLastNonConfigurationInstance() in the new activity instance. If you aretargeting HONEYCOMB or later,consider instead using a Fragment with Fragment.setRetainInstance(boolean.

This function is called purely as anoptimization, and you must not rely on it being called. When it is called, anumber 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'sonDestroy() is called. In particular, no messages will be dispatched during thistime (when the returned object does not have an activity to be associatedwith).

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

These guarantees are designed so that anactivity can use this API to propagate extensive state from the old to newactivity instance, from loaded bitmaps, to network connections, to evenlyactively running threads. Note that you should not propagate any data that may changebased on the configuration, including any data loaded from resources such asstrings, layouts, or drawables.

The guarantee of no message handlingduring the switch to the next activity simplifies use with active objects. Forexample if your retained state is an AsyncTask you are guaranteed that its call backfunctions (like onPostExecute(Result)) will not be called from the call hereuntil you execute the next instance's onCreate(Bundle). (Note however that there is of courseno such guarantee for doInBackground(Params...) since that is running in a separatethread.)

Returns

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

public boolean onSearchRequested ()

Since: APILevel 1

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

You can use this function as a simpleway to launch the search UI, in response to a menu item, search button, orother widgets within your activity. Unless overidden, calling this function isthe same as calling startSearch(null, false, null,false), which launches search for the current activity as specified in itsmanifest, see SearchManager.

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

Returns

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

See Also

·        SearchManager

public boolean onTouchEvent (MotionEvent event)

Since: APILevel 1

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

Parameters

event

The touch screen event being processed.

Returns

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

public boolean onTrackballEvent (MotionEvent event)

Since: APILevel 1

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

Parameters

event

The trackball event being processed.

Returns

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

public void onUserInteraction ()

Since: APILevel 3

Called whenever a key, touch, ortrackball event is dispatched to the activity. Implement this method if youwish to know that the user has interacted with the device in some way whileyour activity is running. This callback and onUserLeaveHint() are intended to help activities managestatus bar notifications intelligently; specifically, for helping activitiesdetermine the proper time to cancel a notfication.

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

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

See Also

·        onUserLeaveHint()

public void onWindowAttributesChanged (WindowManager.LayoutParams params)

Since: APILevel 1

This is called whenever the current window attributeschange.

public void onWindowFocusChanged (booleanhasFocus)

Since: APILevel 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. Thedefault implementation clears the key tracking state, so should always becalled.

Note that this provides informationabout global focus state, which is managed independently of activitylifecycles. As such, while focus changes will generally have some relation tolifecycle changes (an activity that is stopped will not generally get windowfocus), you should not rely on any particular order between the callbacks hereand those in the other lifecycle methods such as onResume().

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

Parameters

hasFocus

Whether the window of this activity has focus.

See Also

·        hasWindowFocus()

·        onResume()

·        onWindowFocusChanged(boolean)

public ActionMode onWindowStartingActionMode (ActionMode.Callback callback)

Since: APILevel 11

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

Note: If you are looking for anotification 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 activitydoes not want to provide special handling for this action mode. (It will behandled by the system.)

public void openContextMenu (View view)

Since: APILevel 1

Programmatically opens the context menufor a particular view. The view should havebeen added via registerForContextMenu(View).

Parameters

view

The view to show the context menu for.

public void openOptionsMenu ()

Since: APILevel 1

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

public void overridePendingTransition (int enterAnim, intexitAnim)

Since: APILevel 5

Call immediately after one of theflavors of startActivity(Intent) or finish() to specify an explicit transitionanimation to perform next.

Parameters

enterAnim

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

exitAnim

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

public void recreate ()

Since: APILevel 11

Cause this Activity to be recreated with a new instance.This results in essentially the same flow as when the Activity is created dueto a configuration change -- the current instance will go through its lifecycleto onDestroy() and a new instance then created afterit.

public void registerForContextMenu (View view)

Since: APILevel 1

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

Parameters

view

The view that should show a context menu.

See Also

·        unregisterForContextMenu(View)

public finalvoid removeDialog (int id)

Since: APILevel 1

Removes any internal references to adialog managed by this Activity. If the dialog is showing, it will dismiss itas part of the clean up.

This can be useful if you know that youwill never show a dialog again and want to avoid the overhead of saving andrestoring it in the future.

As of GINGERBREAD, this function will not throw anexception if you try to remove an ID that does not currently have an associateddialog.

Parameters

id

The id of the managed dialog.

See Also

·        onCreateDialog(int, Bundle)

·        onPrepareDialog(int, Dialog,Bundle)

·        showDialog(int)

·        dismissDialog(int)

public finalboolean requestWindowFeature(int featureId)

Since: APILevel 1

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

Parameters

featureId

The desired feature as defined in Window.

Returns

·        Returns true if the requested feature is supported andnow enabled.

See Also

·        requestFeature(int)

public final void runOnUiThread (Runnable action)

Since: APILevel 1

Runs the specified action on the UIthread. If the current thread is the UI thread, then the action is executedimmediately. If the current thread is not the UI thread, the action is postedto the event queue of the UI thread.

Parameters

action

the action to run on the UI thread

public void setContentView (intlayoutResID)

Since: APILevel 1

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

Parameters

layoutResID

Resource ID to be inflated.

See Also

·        setContentView(android.view.View)

·        setContentView(android.view.View,android.view.ViewGroup.LayoutParams)

public void setContentView (View view)

Since: APILevel 1

Set the activity content to an explicitview. This view is placed directly into the activity's view hierarchy. It canitself be a complex view hierarchy. When calling this method, the layoutparameters of the specified view are ignored. Both the width and the height ofthe view are set by default to MATCH_PARENT. To use your own layout parameters,invoke setContentView(android.view.View,android.view.ViewGroup.LayoutParams) instead.

Parameters

view

The desired content to display.

See Also

·        setContentView(int)

·        setContentView(android.view.View,android.view.ViewGroup.LayoutParams)

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

Since: APILevel 1

Set the activity content to an explicitview. This view is placed directly into the activity's view hierarchy. It canitself be a complex view hierarchy.

Parameters

view

The desired content to display.

params

Layout parameters for the view.

See Also

·        setContentView(android.view.View)

·        setContentView(int)

public finalvoid setDefaultKeyMode(int mode)

Since: APILevel 1

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

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

Parameters

mode

The desired default key mode constant.

See Also

·        DEFAULT_KEYS_DISABLE

·        DEFAULT_KEYS_DIALER

·        DEFAULT_KEYS_SHORTCUT

·        DEFAULT_KEYS_SEARCH_LOCAL

·        DEFAULT_KEYS_SEARCH_GLOBAL

·        onKeyDown(int, KeyEvent)

public finalvoid setFeatureDrawable(int featureId, Drawable drawable)

Since: APILevel 1

Convenience for calling setFeatureDrawable(int, Drawable).

public final void setFeatureDrawableAlpha (int featureId,int alpha)

Since: APILevel 1

Convenience for calling setFeatureDrawableAlpha(int, int).

public finalvoid setFeatureDrawableResource(int featureId, int resId)

Since: APILevel 1

Convenience for calling setFeatureDrawableResource(int,int).

public finalvoid setFeatureDrawableUri(int featureId, Uri uri)

Since: APILevel 1

Convenience for calling setFeatureDrawableUri(int, Uri).

public void setFinishOnTouchOutside (boolean finish)

Since: APILevel 11

Sets whether this activity is finished when touchedoutside its window's bounds.

public void setIntent (Intent newIntent)

Since: APILevel 1

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

Parameters

newIntent

The new Intent object to return from getIntent

See Also

·        getIntent()

·        onNewIntent(Intent)

public finalvoid setProgress (int progress)

Since: APILevel 1

Sets the progress for the progress barsin the title.

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

Parameters

progress

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

public finalvoid setProgressBarIndeterminate(boolean indeterminate)

Since: APILevel 1

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

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

Parameters

indeterminate

Whether the horizontal progress bar should be indeterminate.

public finalvoid setProgressBarIndeterminateVisibility(boolean visible)

Since: APILevel 1

Sets the visibility of the indeterminateprogress bar in the title.

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

Parameters

visible

Whether to show the progress bars in the title.

public final void setProgressBarVisibility (booleanvisible)

Since: APILevel 1

Sets the visibility of the progress barin the title.

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

Parameters

visible

Whether to show the progress bars in the title.

public void setRequestedOrientation (intrequestedOrientation)

Since: APILevel 1

Change the desired orientation of thisactivity. If the activity is currently in the foreground or otherwise impactingthe screen orientation, the screen will immediately be changed (possiblycausing the activity to be restarted). Otherwise, this will be used the nexttime the activity is visible.

Parameters

requestedOrientation

An orientation constant as used in ActivityInfo.screenOrientation.

public finalvoid setResult (int resultCode)

Since: APILevel 1

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

Parameters

resultCode

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

See Also

·        RESULT_CANCELED

·        RESULT_OK

·        RESULT_FIRST_USER

·        setResult(int, Intent)

public finalvoid setResult (int resultCode,Intent data)

Since: APILevel 1

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

Parameters

resultCode

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

data

The data to propagate back to the originating activity.

See Also

·        RESULT_CANCELED

·        RESULT_OK

·        RESULT_FIRST_USER

·        setResult(int)

public finalvoid setSecondaryProgress(int secondaryProgress)

Since: APILevel 1

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

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

Parameters

secondaryProgress

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

public void setTitle (int titleId)

Since: APILevel 1

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

public void setTitle (CharSequence title)

Since: APILevel 1

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

public void setTitleColor (int textColor)

Since: APILevel 1

public void setVisible (booleanvisible)

Since: APILevel 3

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

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

public finalvoid setVolumeControlStream(int streamType)

Since: APILevel 1

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

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

Parameters

streamType

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

public finalboolean showDialog (int id, Bundle args)

Since: APILevel 8

Show a dialog managed by this activity.A call to onCreateDialog(int, Bundle) will be made with the same id the firsttime this is called for a given id. From thereafter, the dialog will be automaticallysaved and restored. If you are targeting HONEYCOMB or later,consider instead using a DialogFragment instead.

Each time a dialog is shown, onPrepareDialog(int, Dialog,Bundle) will be made to provide an opportunity to do any timely preparation.

Parameters

id

The id of the managed dialog.

args

Arguments to pass through to the dialog. These will be saved and restored for you. Note that if the dialog is already created, onCreateDialog(int, Bundle) will not be called with the new arguments but onPrepareDialog(int, Dialog, Bundle) will be. If you need to rebuild the dialog, call removeDialog(int) first.

Returns

·        Returns true if the Dialog was created; false is returnedif it is not created because onCreateDialog(int, Bundle) returns false.

See Also

·        Dialog

·        onCreateDialog(int, Bundle)

·        onPrepareDialog(int, Dialog,Bundle)

·        dismissDialog(int)

·        removeDialog(int)

public finalvoid showDialog (int id)

Since: APILevel 1

Simple version of showDialog(int, Bundle) that does not take any arguments.Simply calls showDialog(int, Bundle) with null arguments.

public ActionMode startActionMode (ActionMode.Callback callback)

Since: APILevel 11

Start an action mode.

Parameters

callback

Callback that will manage lifecycle events for this context mode

Returns

·        The ContextMode that was started, or null if it wascanceled

See Also

·        ActionMode

public void startActivities (Intent[] intents)

Since: APILevel 11

Launch a new activity. You will notreceive any information about when the activity exits. This implementationoverrides the base version, providing information about the activity performingthe launch. Because of this additional information, the FLAG_ACTIVITY_NEW_TASK launch flag is not required; if notspecified, the new activity will be added to the task of the caller.

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

Parameters

intents

The intents to start.

Throws

 

android.content.ActivityNotFoundException

See Also

·        startActivityForResult(Intent,int)

public void startActivity (Intent intent)

Since: APILevel 1

Launch a new activity. You will notreceive any information about when the activity exits. This implementationoverrides the base version, providing information about the activity performingthe launch. Because of this additional information, the FLAG_ACTIVITY_NEW_TASK launch flag is not required; if notspecified, the new activity will be added to the task of the caller.

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

Parameters

intent

The intent to start.

Throws

 

android.content.ActivityNotFoundException

See Also

·        startActivityForResult(Intent,int)

public void startActivityForResult (Intent intent, intrequestCode)

Since: APILevel 1

Launch an activity for which you wouldlike a result when it finished. When this activity exits, youronActivityResult() method will be called with the given requestCode. Using anegative requestCode is the same as calling startActivity(Intent) (the activity is not launched as asub-activity).

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

As a special case, if you callstartActivityForResult() with a requestCode >= 0 during the initialonCreate(Bundle savedInstanceState)/onResume() of your activity, then yourwindow will not be displayed until a result is returned back from the startedactivity. This is to avoid visible flickering when redirecting to anotheractivity.

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

Parameters

intent

The intent to start.

requestCode

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

Throws

 

android.content.ActivityNotFoundException

See Also

·        startActivity(Intent)

public void startActivityFromChild (Activity child, Intent intent, intrequestCode)

Since: APILevel 1

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

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

Parameters

child

The activity making the call.

intent

The intent to start.

requestCode

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

Throws

 

android.content.ActivityNotFoundException

See Also

·        startActivity(Intent)

·        startActivityForResult(Intent,int)

public void startActivityFromFragment (Fragment fragment, Intent intent, intrequestCode)

Since: APILevel 11

This is called when a Fragment in thisactivity calls its startActivity(Intent) or startActivityForResult(Intent,int) method.

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

Parameters

fragment

The fragment making the call.

intent

The intent to start.

requestCode

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

Throws

 

android.content.ActivityNotFoundException

See Also

·        startActivity(Intent)

·        startActivityForResult(Intent,int)

public boolean startActivityIfNeeded (Intent intent, intrequestCode)

Since: APILevel 1

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

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

Parameters

intent

The intent to start.

requestCode

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

Returns

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

See Also

·        startActivity(Intent)

·        startActivityForResult(Intent,int)

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

Since: APILevel 5

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

Parameters

intent

The IntentSender to launch.

fillInIntent

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

flagsMask

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

flagsValues

Desired values for any bits set in flagsMask

extraFlags

Always set to 0.

Throws

IntentSender.SendIntentException

 

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

Since: APILevel 5

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

Parameters

intent

The IntentSender to launch.

requestCode

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

fillInIntent

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

flagsMask

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

flagsValues

Desired values for any bits set in flagsMask

extraFlags

Always set to 0.

Throws

IntentSender.SendIntentException

 

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

Since: APILevel 5

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

Throws

IntentSender.SendIntentException

 

public void startManagingCursor (Cursor c)

Since: APILevel 1

This method isdeprecated.
Use
CursorLoader instead.

This method allows the activity to takecare of managing the given Cursor's lifecycle for you based on theactivity's lifecycle. That is, when the activity is stopped it willautomatically call deactivate() on the given Cursor, and when it islater restarted it will call requery() for you. When the activity isdestroyed, all managed Cursors will be closed automatically. If you aretargeting HONEYCOMB or later,consider instead using LoaderManager instead,available via getLoaderManager().

Parameters

c

The Cursor to be managed.

See Also

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

·        stopManagingCursor(Cursor)

public boolean startNextMatchingActivity (Intent intent)

Since: APILevel 1

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

Parameters

intent

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

Returns

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

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

Since: APILevel 1

This hook is called to launch the searchUI.

It is typically called fromonSearchRequested(), either directly from Activity.onSearchRequested() or froman overridden version in any given Activity. If your goal is simply to activatesearch, it is preferred to call onSearchRequested(), which may have beenoverriden elsewhere in your Activity. If your goal is to inject specific datasuch as context data, it is preferred to override onSearchRequested(),so that any callers to it will benefit from the override.

Parameters

initialQuery

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

selectInitialQuery

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

appSearchData

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

globalSearch

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

See Also

·        SearchManager

·        onSearchRequested()

public void stopManagingCursor (Cursor c)

Since: APILevel 1

This method isdeprecated.
Use
CursorLoader instead.

Given a Cursor that was previously givento startManagingCursor(Cursor), stop the activity's management of thatcursor.

Parameters

c

The Cursor that was being managed.

See Also

·        startManagingCursor(Cursor)

public void takeKeyEvents (boolean get)

Since: APILevel 1

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

See Also

·        takeKeyEvents(boolean)

public void triggerSearch (String query, Bundle appSearchData)

Since: APILevel 5

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

Parameters

query

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

appSearchData

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

public void unregisterForContextMenu (View view)

Since: APILevel 1

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

Parameters

view

The view that should stop showing a context menu.

See Also

·        registerForContextMenu(View)

Protected Methods

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

Since: APILevel 1

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

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

Parameters

requestCode

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

resultCode

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

data

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

See Also

·        startActivityForResult(Intent,int)

·        createPendingResult(int, Intent,int)

·        setResult(int)

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

Since: APILevel 1

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

Parameters

theme

The Theme object being modified.

resid

The theme style resource being applied to theme.

first

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

protected void onChildTitleChanged (Activity childActivity, CharSequence title)

Since: APILevel 1

protected void onCreate (BundlesavedInstanceState)

Since: APILevel 1

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

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

Derived classesmust call through to the super class's implementation of this method. If theydo not, an exception will be thrown.

Parameters

savedInstanceState

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

See Also

·        onStart()

·        onSaveInstanceState(Bundle)

·        onRestoreInstanceState(Bundle)

·        onPostCreate(Bundle)

protected Dialog onCreateDialog (int id)

Since: APILevel 1

This method isdeprecated.
Old no-arguments version of
onCreateDialog(int, Bundle).

protected Dialog onCreateDialog (int id, Bundle args)

Since: APILevel 8

Callback for creating dialogs that aremanaged (saved and restored) for you by the activity. The defaultimplementation calls through to onCreateDialog(int) for compatibility. If you aretargeting HONEYCOMB or later,consider instead using a DialogFragment instead.

If you use showDialog(int), the activity will call through to thismethod the first time, and hang onto it thereafter. Any dialog that is createdby this method will automatically be saved and restored for you, includingwhether it is showing.

If you would like the activity to managesaving and restoring dialogs for you, you should override this method andhandle any ids that are passed to showDialog(int).

If you would like an opportunity toprepare your dialog before it is shown, override onPrepareDialog(int, Dialog,Bundle).

Parameters

id

The id of the dialog.

args

The dialog arguments provided to showDialog(int, Bundle).

Returns

·        The dialog. If you return null, the dialog will not becreated.

See Also

·        onPrepareDialog(int, Dialog,Bundle)

·        showDialog(int, Bundle)

·        dismissDialog(int)

·        removeDialog(int)

protected void onDestroy ()

Since: APILevel 1

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

Note: do notcount on this method being called as a place for saving data! For example, ifan activity is editing data in a content provider, those edits should becommitted in either onPause() or onSaveInstanceState(Bundle), not here. This method is usually implemented tofree resources like threads that are associated with an activity, so that adestroyed activity does not leave such things around while the rest of itsapplication is still running. There are situations where the system will simplykill 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 aroundafter the process goes away.

Derived classesmust call through to the super class's implementation of this method. If theydo not, an exception will be thrown.

See Also

·        onPause()

·        onStop()

·        finish()

·        isFinishing()

protected void onNewIntent (Intent intent)

Since: APILevel 1

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

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

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

Parameters

intent

The new intent that was started for the activity.

See Also

·        getIntent()

·        setIntent(Intent)

·        onResume()

protected void onPause ()

Since: APILevel 1

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

When activity B is launched in front ofactivity A, this callback will be invoked on A. B will not be created until A'sonPause() returns, so be sure to not do anythinglengthy here.

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

In situations where the system needsmore 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 fromthis function. In general onSaveInstanceState(Bundle) is used to save per-instance state inthe activity and this method is used to store global persistent data (incontent providers, files, etc.)

After receiving this call you willusually receive a following call to onStop() (after the next activity has beenresumed and displayed), however in some cases there will be a direct call backto onResume() without going through the stoppedstate.

Derived classesmust call through to the super class's implementation of this method. If theydo not, an exception will be thrown.

See Also

·        onResume()

·        onSaveInstanceState(Bundle)

·        onStop()

protected void onPostCreate (BundlesavedInstanceState)

Since: APILevel 1

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

Derived classesmust call through to the super class's implementation of this method. If theydo not, an exception will be thrown.

Parameters

savedInstanceState

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

See Also

·        onCreate(Bundle)

protected void onPostResume ()

Since: APILevel 1

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

Derived classesmust call through to the super class's implementation of this method. If theydo not, an exception will be thrown.

See Also

·        onResume()

protected void onPrepareDialog (int id, Dialog dialog)

Since: APILevel 1

This method isdeprecated.
Old no-arguments version of
onPrepareDialog(int, Dialog,Bundle).

protected void onPrepareDialog (int id, Dialog dialog, Bundle args)

Since: APILevel 8

Provides an opportunity to prepare amanaged dialog before it is being shown. The default implementation callsthrough to onPrepareDialog(int, Dialog) for compatibility.

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

Parameters

id

The id of the managed dialog.

dialog

The dialog.

args

The dialog arguments provided to showDialog(int, Bundle).

See Also

·        onCreateDialog(int, Bundle)

·        showDialog(int)

·        dismissDialog(int)

·        removeDialog(int)

protected void onRestart ()

Since: APILevel 1

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

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

Derived classesmust call through to the super class's implementation of this method. If theydo not, an exception will be thrown.

See Also

·        onStop()

·        onStart()

·        onResume()

protected void onRestoreInstanceState (BundlesavedInstanceState)

Since: APILevel 1

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

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

Parameters

savedInstanceState

the data most recently supplied in onSaveInstanceState(Bundle).

See Also

·        onCreate(Bundle)

·        onPostCreate(Bundle)

·        onResume()

·        onSaveInstanceState(Bundle)

protected void onResume ()

Since: APILevel 1

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

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

Derived classesmust call through to the super class's implementation of this method. If theydo not, an exception will be thrown.

See Also

·        onRestoreInstanceState(Bundle)

·        onRestart()

·        onPostResume()

·        onPause()

protected void onSaveInstanceState (Bundle outState)

Since: APILevel 1

Called to retrieve per-instance statefrom 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 passedto both).

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

Do not confuse this method with activitylifecycle callbacks such as onPause(), which is always called when anactivity is being placed in the background or on its way to destruction, or onStop() which is called before destruction. Oneexample of when onPause() and onStop() is called and not this method is when auser navigates back from activity B to activity A: there is no need to call onSaveInstanceState(Bundle) on B because that particular instancewill 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 frontof activity A: the system may avoid calling onSaveInstanceState(Bundle) on activity A if it isn't killed duringthe lifetime of B since the state of the user interface of A will stay intact.

The default implementation takes care ofmost of the UI per-instance state for you by calling onSaveInstanceState() on each view in the hierarchy that hasan id, and by saving the id of the currently focused view (all of which isrestored by the default implementation of onRestoreInstanceState(Bundle)). If you override this method to saveadditional information not captured by each individual view, you will likelywant to call through to the default implementation, otherwise be prepared tosave all of the state of each view yourself.

If called, this method will occur beforeonStop(). There are no guarantees about whetherit will occur before or after onPause().

Parameters

outState

Bundle in which to place your saved state.

See Also

·        onCreate(Bundle)

·        onRestoreInstanceState(Bundle)

·        onPause()

protected void onStart ()

Since: APILevel 1

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

Derived classesmust call through to the super class's implementation of this method. If theydo not, an exception will be thrown.

See Also

·        onCreate(Bundle)

·        onStop()

·        onResume()

protected void onStop ()

Since: APILevel 1

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

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

Derived classesmust call through to the super class's implementation of this method. If theydo not, an exception will be thrown.

See Also

·        onRestart()

·        onResume()

·        onSaveInstanceState(Bundle)

·        onDestroy()

protected void onTitleChanged (CharSequence title, intcolor)

Since: APILevel 1

protected void onUserLeaveHint ()

Since: APILevel 3

Called as part of the activity lifecyclewhen an activity is about to go into the background as the result of userchoice. For example, when the user presses the Home key, onUserLeaveHint() will be called, but when an incomingphone call causes the in-call Activity to be automatically brought to theforeground, onUserLeaveHint() will not be called on the activitybeing interrupted. In cases when it is invoked, this method is called rightbefore the activity's onPause() callback.

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

See Also

·        onUserInteraction()