public class Activity extends ContextThemeWrapper implements LayoutInflater.Factory2, Window.Callback, KeyEvent.Callback, View.OnCreateContextMenuListener, ComponentCallbacks2, Window.OnWindowDismissedCallback, Window.WindowControllerCallback
setContentView(int)
. While activities are often presented to the user
as full-screen windows, they can also be used in other ways: as floating
windows (via a theme with android.R.attr#windowIsFloating
set)
or embedded inside of another activity (using ActivityGroup
).
There are two methods almost all subclasses of Activity will implement:
onCreate(android.os.Bundle)
is where you initialize your activity. Most
importantly, here you will usually call setContentView(int)
with a layout resource defining your UI, and using findViewById(int)
to retrieve the widgets in that UI that you need to interact with
programmatically.
onPause()
is where you deal with the user leaving your
activity. Most importantly, any changes made by the user should at this
point be committed (usually to the
ContentProvider
holding the data).
To be of use with Context.startActivity()
, all
activity classes must have a corresponding
<activity>
declaration in their package's AndroidManifest.xml
.
Topics covered here:
The Activity class is an important part of an application's overall lifecycle, and the way activities are launched and put together is a fundamental part of the platform's application model. For a detailed perspective on the structure of an Android application and how activities behave, please read the Application Fundamentals and Tasks and Back Stack developer guides.
You can also find a detailed discussion about how to create activities in the Activities developer guide.
Starting with Build.VERSION_CODES.HONEYCOMB
, Activity
implementations can make use of the Fragment
class to better
modularize their code, build more sophisticated user interfaces for larger
screens, and help scale their application between small and large screens.
Activities in the system are managed as an activity stack. When a new activity is started, it is placed on the top of the stack and becomes the running activity -- the previous activity always remains below it in the stack, and will not come to the foreground again until the new activity exits.
An activity has essentially four states:
The following diagram shows the important state paths of an Activity. The square rectangles represent callback methods you can implement to perform operations when the Activity moves between states. The colored ovals are major states the Activity can be in.
There are three key loops you may be interested in monitoring within your activity:
onCreate(android.os.Bundle)
through to a single final call
to onDestroy()
. An activity will do all setup
of "global" state in onCreate(), and release all remaining resources in
onDestroy(). For example, if it has a thread running in the background
to download data from the network, it may create that thread in onCreate()
and then stop the thread in onDestroy().
onStart()
until a corresponding call to
onStop()
. During this time the user can see the
activity on-screen, though it may not be in the foreground and interacting
with the user. Between these two methods you can maintain resources that
are needed to show the activity to the user. For example, you can register
a BroadcastReceiver
in onStart() to monitor for changes
that impact your UI, and unregister it in onStop() when the user no
longer sees what you are displaying. The onStart() and onStop() methods
can be called multiple times, as the activity becomes visible and hidden
to the user.
onResume()
until a corresponding call to
onPause()
. During this time the activity is
in front of all other activities and interacting with the user. An activity
can frequently go between the resumed and paused states -- for example when
the device goes to sleep, when an activity result is delivered, when a new
intent is delivered -- so the code in these methods should be fairly
lightweight.
The entire lifecycle of an activity is defined by the following
Activity methods. All of these are hooks that you can override
to do appropriate work when the activity changes state. All
activities will implement onCreate(android.os.Bundle)
to do their initial setup; many will also implement
onPause()
to commit changes to data and
otherwise prepare to stop interacting with the user. You should always
call up to your superclass when implementing these methods.
public class Activity extends ApplicationContext { protected void onCreate(Bundle savedInstanceState); protected void onStart(); protected void onRestart(); protected void onResume(); protected void onPause(); protected void onStop(); protected void onDestroy(); }
In general the movement through an activity's lifecycle looks like this:
Method | Description | Killable? | Next | ||
---|---|---|---|---|---|
onCreate() |
Called when the activity is first created.
This is where you should do all of your normal static set up:
create views, bind data to lists, etc. This method also
provides you with a Bundle containing the activity's previously
frozen state, if there was one.
Always followed by |
No | onStart() |
||
onRestart() |
Called after your activity has been stopped, prior to it being
started again.
Always followed by |
No | onStart() |
||
onStart() |
Called when the activity is becoming visible to the user.
Followed by |
No | onResume() or onStop() |
||
onResume() |
Called when the activity will start
interacting with the user. At this point your activity is at
the top of the activity stack, with user input going to it.
Always followed by |
No | onPause() |
||
onPause() |
Called when the system is about to start resuming a previous
activity. This is typically used to commit unsaved changes to
persistent data, stop animations and other things that may be consuming
CPU, etc. Implementations of this method must be very quick because
the next activity will not be resumed until this method returns.
Followed by either |
Pre-Build.VERSION_CODES.HONEYCOMB |
onResume() oronStop() |
||
onStop() |
Called when the activity is no longer visible to the user, because
another activity has been resumed and is covering this one. This
may happen either because a new activity is being started, an existing
one is being brought in front of this one, or this one is being
destroyed.
Followed by either |
Yes | onRestart() oronDestroy() |
||
onDestroy() |
The final call you receive before your
activity is destroyed. This can happen either because the
activity is finishing (someone called finish(int) on
it, or because the system is temporarily destroying this
instance of the activity to save space. You can distinguish
between these two scenarios with the isFinishing() method. |
Yes | nothing |
Note the "Killable" column in the above table -- for those methods that
are marked as being killable, after that method returns the process hosting the
activity may be killed by the system at any time without another line
of its code being executed. Because of this, you should use the
onPause()
method to write any persistent data (such as user edits)
to storage. In addition, the method
onSaveInstanceState(Bundle)
is called before placing the activity
in such a background state, allowing you to save away any dynamic instance
state in your activity into the given Bundle, to be later received in
onCreate(android.os.Bundle)
if the activity needs to be re-created.
See the Process Lifecycle
section for more information on how the lifecycle of a process is tied
to the activities it is hosting. Note that it is important to save
persistent data in onPause()
instead of onSaveInstanceState(android.os.Bundle)
because the latter is not part of the lifecycle callbacks, so will not
be called in every situation as described in its documentation.
Be aware that these semantics will change slightly between
applications targeting platforms starting with Build.VERSION_CODES.HONEYCOMB
vs. those targeting prior platforms. Starting with Honeycomb, an application
is not in the killable state until its onStop()
has returned. This
impacts when onSaveInstanceState(Bundle)
may be called (it may be
safely called after onPause()
and allows and application to safely
wait until onStop()
to save persistent state.
For those methods that are not marked as being killable, the activity's
process will not be killed by the system starting from the time the method
is called and continuing after it returns. Thus an activity is in the killable
state, for example, between after onPause()
to the start of
onResume()
.
If the configuration of the device (as defined by the
Resources.Configuration
class) changes,
then anything displaying a user interface will need to update to match that
configuration. Because Activity is the primary mechanism for interacting
with the user, it includes special support for handling configuration
changes.
Unless you specify otherwise, a configuration change (such as a change
in screen orientation, language, input devices, etc) will cause your
current activity to be destroyed, going through the normal activity
lifecycle process of onPause()
,
onStop()
, and onDestroy()
as appropriate. If the activity
had been in the foreground or visible to the user, once onDestroy()
is
called in that instance then a new instance of the activity will be
created, with whatever savedInstanceState the previous instance had generated
from onSaveInstanceState(android.os.Bundle)
.
This is done because any application resource, including layout files, can change based on any configuration value. Thus the only safe way to handle a configuration change is to re-retrieve all resources, including layouts, drawables, and strings. Because activities must already know how to save their state and re-create themselves from that state, this is a convenient way to have an activity restart itself with a new configuration.
In some special cases, you may want to bypass restarting of your
activity based on one or more types of configuration changes. This is
done with the android:configChanges
attribute in its manifest. For any types of configuration changes you say
that you handle there, you will receive a call to your current activity's
onConfigurationChanged(android.content.res.Configuration)
method instead of being restarted. If
a configuration change involves any that you do not handle, however, the
activity will still be restarted and onConfigurationChanged(android.content.res.Configuration)
will not be called.
The startActivity(android.content.Intent)
method is used to start a
new activity, which will be placed at the top of the activity stack. It
takes a single argument, an Intent
,
which describes the activity
to be executed.
Sometimes you want to get a result back from an activity when it
ends. For example, you may start an activity that lets the user pick
a person in a list of contacts; when it ends, it returns the person
that was selected. To do this, you call the
startActivityForResult(Intent, int)
version with a second integer parameter identifying the call. The result
will come back through your onActivityResult(int, int, android.content.Intent)
method.
When an activity exits, it can call
setResult(int)
to return data back to its parent. It must always supply a result code,
which can be the standard results RESULT_CANCELED, RESULT_OK, or any
custom values starting at RESULT_FIRST_USER. In addition, it can optionally
return back an Intent containing any additional data it wants. All of this
information appears back on the
parent's Activity.onActivityResult()
, along with the integer
identifier it originally supplied.
If a child activity fails for any reason (such as crashing), the parent activity will receive a result with the code RESULT_CANCELED.
public class MyActivity extends Activity { ... static final int PICK_CONTACT_REQUEST = 0; public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER) { // When the user center presses, let them pick a contact. startActivityForResult( new Intent(Intent.ACTION_PICK, new Uri("content://contacts")), PICK_CONTACT_REQUEST); return true; } return false; } protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == PICK_CONTACT_REQUEST) { if (resultCode == RESULT_OK) { // A contact was picked. Here we will just display it // to the user. startActivity(new Intent(Intent.ACTION_VIEW, data)); } } } }
There are generally two kinds of persistent state than an activity will deal with: shared document-like data (typically stored in a SQLite database using a content provider) and internal state such as user preferences.
For content provider data, we suggest that activities use a "edit in place" user model. That is, any edits a user makes are effectively made immediately without requiring an additional confirmation step. Supporting this model is generally a simple matter of following two rules:
When creating a new document, the backing database entry or file for it is created immediately. For example, if the user chooses to write a new e-mail, a new entry for that e-mail is created as soon as they start entering data, so that if they go to any other activity after that point this e-mail will now appear in the list of drafts.
When an activity's onPause()
method is called, it should
commit to the backing content provider or file any changes the user
has made. This ensures that those changes will be seen by any other
activity that is about to run. You will probably want to commit
your data even more aggressively at key times during your
activity's lifecycle: for example before starting a new
activity, before finishing your own activity, when the user
switches between input fields, etc.
This model is designed to prevent data loss when a user is navigating between activities, and allows the system to safely kill an activity (because system resources are needed somewhere else) at any time after it has been paused. Note this implies that the user pressing BACK from your activity does not mean "cancel" -- it means to leave the activity with its current contents saved away. Canceling edits in an activity must be provided through some other mechanism, such as an explicit "revert" or "undo" option.
See the content package for more information about content providers. These are a key aspect of how different activities invoke and propagate data between themselves.
The Activity class also provides an API for managing internal persistent state associated with an activity. This can be used, for example, to remember the user's preferred initial display in a calendar (day view or week view) or the user's default home page in a web browser.
Activity persistent state is managed
with the method getPreferences(int)
,
allowing you to retrieve and
modify a set of name/value pairs associated with the activity. To use
preferences that are shared across multiple application components
(activities, receivers, services, providers), you can use the underlying
Context.getSharedPreferences()
method
to retrieve a preferences
object stored under a specific name.
(Note that it is not possible to share settings data across application
packages -- for that you will need a content provider.)
Here is an excerpt from a calendar activity that stores the user's preferred view mode in its persistent settings:
public class CalendarActivity extends Activity { ... static final int DAY_VIEW_MODE = 0; static final int WEEK_VIEW_MODE = 1; private SharedPreferences mPrefs; private int mCurViewMode; protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); SharedPreferences mPrefs = getSharedPreferences(); mCurViewMode = mPrefs.getInt("view_mode", DAY_VIEW_MODE); } protected void onPause() { super.onPause(); SharedPreferences.Editor ed = mPrefs.edit(); ed.putInt("view_mode", mCurViewMode); ed.commit(); } }
The ability to start a particular Activity can be enforced when it is
declared in its
manifest's <activity>
tag. By doing so, other applications will need to declare a corresponding
<uses-permission>
element in their own manifest to be able to start that activity.
When starting an Activity you can set Intent.FLAG_GRANT_READ_URI_PERMISSION
and/or Intent.FLAG_GRANT_WRITE_URI_PERMISSION
on the Intent. This will grant the
Activity access to the specific URIs in the Intent. Access will remain
until the Activity has finished (it will remain across the hosting
process being killed and other temporary destruction). As of
Build.VERSION_CODES.GINGERBREAD
, if the Activity
was already created and a new Intent is being delivered to
onNewIntent(Intent)
, any newly granted URI permissions will be added
to the existing ones it holds.
See the Security and Permissions document for more information on permissions and security in general.
The Android system attempts to keep application process around for as long as possible, but eventually will need to remove old processes when memory runs low. As described in Activity Lifecycle, the decision about which process to remove is intimately tied to the state of the user's interaction with it. In general, there are four states a process can be in based on the activities running in it, listed here in order of importance. The system will kill less important processes (the last ones) before it resorts to killing more important processes (the first ones).
The foreground activity (the activity at the top of the screen that the user is currently interacting with) is considered the most important. Its process will only be killed as a last resort, if it uses more memory than is available on the device. Generally at this point the device has reached a memory paging state, so this is required in order to keep the user interface responsive.
A visible activity (an activity that is visible to the user but not in the foreground, such as one sitting behind a foreground dialog) is considered extremely important and will not be killed unless that is required to keep the foreground activity running.
A background activity (an activity that is not visible to
the user and has been paused) is no longer critical, so the system may
safely kill its process to reclaim memory for other foreground or
visible processes. If its process needs to be killed, when the user navigates
back to the activity (making it visible on the screen again), its
onCreate(android.os.Bundle)
method will be called with the savedInstanceState it had previously
supplied in onSaveInstanceState(android.os.Bundle)
so that it can restart itself in the same
state as the user last left it.
An empty process is one hosting no activities or other
application components (such as Service
or
BroadcastReceiver
classes). These are killed very
quickly by the system as memory becomes low. For this reason, any
background operation you do outside of an activity must be executed in the
context of an activity BroadcastReceiver or Service to ensure that the system
knows it needs to keep your process around.
Sometimes an Activity may need to do a long-running operation that exists
independently of the activity lifecycle itself. An example may be a camera
application that allows you to upload a picture to a web site. The upload
may take a long time, and the application should allow the user to leave
the application while it is executing. To accomplish this, your Activity
should start a Service
in which the upload takes place. This allows
the system to properly prioritize your process (considering it to be more
important than other non-visible applications) for the duration of the
upload, independent of whether the original activity is paused, stopped,
or finished.
Modifier and Type | Class and Description |
---|---|
static interface |
Activity.TranslucentConversionListener
Interface for informing a translucent
Activity once all visible activities below it
have completed drawing. |
Context.BindServiceFlags, Context.CreatePackageOptions, Context.ServiceName
Modifier and Type | Field and Description |
---|---|
static int |
DEFAULT_KEYS_DIALER
Use with
setDefaultKeyMode(int) to launch the dialer during default
key handling. |
static int |
DEFAULT_KEYS_DISABLE
Use with
setDefaultKeyMode(int) to turn off default handling of
keys. |
static 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. |
static int |
DEFAULT_KEYS_SEARCH_LOCAL
Use with
setDefaultKeyMode(int) to specify that unhandled keystrokes
will start an application-defined search. |
static int |
DEFAULT_KEYS_SHORTCUT
Use with
setDefaultKeyMode(int) to execute a menu shortcut in
default key handling. |
static int |
DONT_FINISH_TASK_WITH_ACTIVITY |
static int |
FINISH_TASK_WITH_ACTIVITY |
static int |
FINISH_TASK_WITH_ROOT_ACTIVITY |
protected static int[] |
FOCUSED_STATE_SET |
static int |
RESULT_CANCELED
Standard activity result: operation canceled.
|
static int |
RESULT_FIRST_USER
Start of user-defined activity results.
|
static int |
RESULT_OK
Standard activity result: operation succeeded.
|
ACCESSIBILITY_SERVICE, ACCOUNT_SERVICE, ACTIVITY_SERVICE, ALARM_SERVICE, APP_OPS_SERVICE, APPWIDGET_SERVICE, AUDIO_SERVICE, BACKUP_SERVICE, BATTERY_SERVICE, BIND_ABOVE_CLIENT, BIND_ADJUST_WITH_ACTIVITY, BIND_ALLOW_OOM_MANAGEMENT, BIND_ALLOW_WHITELIST_MANAGEMENT, BIND_AUTO_CREATE, BIND_DEBUG_UNBIND, BIND_EXTERNAL_SERVICE, BIND_FOREGROUND_SERVICE, BIND_FOREGROUND_SERVICE_WHILE_AWAKE, BIND_IMPORTANT, BIND_NOT_FOREGROUND, BIND_NOT_VISIBLE, BIND_SHOWING_UI, BIND_TREAT_LIKE_ACTIVITY, BIND_VISIBLE, BIND_WAIVE_PRIORITY, BLUETOOTH_SERVICE, CAMERA_SERVICE, CAPTIONING_SERVICE, CARRIER_CONFIG_SERVICE, CLIPBOARD_SERVICE, CONNECTIVITY_SERVICE, CONSUMER_IR_SERVICE, CONTEXT_CREDENTIAL_PROTECTED_STORAGE, CONTEXT_DEVICE_PROTECTED_STORAGE, CONTEXT_IGNORE_SECURITY, CONTEXT_INCLUDE_CODE, CONTEXT_REGISTER_PACKAGE, CONTEXT_RESTRICTED, CONTEXTHUB_SERVICE, COUNTRY_DETECTOR, DEVICE_IDLE_CONTROLLER, DEVICE_POLICY_SERVICE, DISPLAY_SERVICE, DOWNLOAD_SERVICE, DROPBOX_SERVICE, ETHERNET_SERVICE, FINGERPRINT_SERVICE, GATEKEEPER_SERVICE, HARDWARE_PROPERTIES_SERVICE, HDMI_CONTROL_SERVICE, INPUT_METHOD_SERVICE, INPUT_SERVICE, JOB_SCHEDULER_SERVICE, KEYGUARD_SERVICE, LAUNCHER_APPS_SERVICE, LAYOUT_INFLATER_SERVICE, LOCATION_SERVICE, MEDIA_PROJECTION_SERVICE, MEDIA_ROUTER_SERVICE, MEDIA_SESSION_SERVICE, MIDI_SERVICE, MODE_APPEND, MODE_ENABLE_WRITE_AHEAD_LOGGING, MODE_MULTI_PROCESS, MODE_NO_LOCALIZED_COLLATORS, MODE_PRIVATE, MODE_WORLD_READABLE, MODE_WORLD_WRITEABLE, NETWORK_POLICY_SERVICE, NETWORK_SCORE_SERVICE, NETWORK_STATS_SERVICE, NETWORKMANAGEMENT_SERVICE, NFC_SERVICE, NOTIFICATION_SERVICE, NSD_SERVICE, PERSISTENT_DATA_BLOCK_SERVICE, POWER_SERVICE, PRINT_SERVICE, RADIO_SERVICE, RECOVERY_SERVICE, RESTRICTIONS_SERVICE, SEARCH_SERVICE, SENSOR_SERVICE, SERIAL_SERVICE, SHORTCUT_SERVICE, SIP_SERVICE, SOUND_TRIGGER_SERVICE, STATUS_BAR_SERVICE, STORAGE_SERVICE, SYSTEM_HEALTH_SERVICE, TELECOM_SERVICE, TELEPHONY_SERVICE, TELEPHONY_SUBSCRIPTION_SERVICE, TEXT_SERVICES_MANAGER_SERVICE, TRUST_SERVICE, TV_INPUT_SERVICE, UI_MODE_SERVICE, UPDATE_LOCK_SERVICE, USAGE_STATS_SERVICE, USB_SERVICE, USER_SERVICE, VIBRATOR_SERVICE, VOICE_INTERACTION_MANAGER_SERVICE, WALLPAPER_SERVICE, WIFI_NAN_SERVICE, WIFI_P2P_SERVICE, WIFI_RTT_SERVICE, WIFI_SCANNING_SERVICE, WIFI_SERVICE, WINDOW_SERVICE
TRIM_MEMORY_BACKGROUND, TRIM_MEMORY_COMPLETE, TRIM_MEMORY_MODERATE, TRIM_MEMORY_RUNNING_CRITICAL, TRIM_MEMORY_RUNNING_LOW, TRIM_MEMORY_RUNNING_MODERATE, TRIM_MEMORY_UI_HIDDEN
Constructor and Description |
---|
Activity() |
Modifier and Type | Method and Description |
---|---|
void |
addContentView(View view,
ViewGroup.LayoutParams params)
Add an additional content view to the activity.
|
boolean |
canStartActivityForResult()
Identifies whether this Context instance will be able to process calls to
Context.startActivityForResult(String, Intent, int, Bundle) . |
void |
closeContextMenu()
Programmatically closes the most recently opened context menu, if showing.
|
void |
closeOptionsMenu()
Progammatically closes the options menu.
|
void |
convertFromTranslucent()
Convert a translucent themed Activity
android.R.attr#windowIsTranslucent to a
fullscreen opaque Activity. |
boolean |
convertToTranslucent(Activity.TranslucentConversionListener callback,
ActivityOptions options)
Convert a translucent themed Activity
android.R.attr#windowIsTranslucent back from
opaque to translucent following a call to convertFromTranslucent() . |
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, android.content.Intent) callback. |
void |
dismissDialog(int id)
Deprecated.
Use the new
DialogFragment class with
FragmentManager instead; this is also
available on older platforms through the Android compatibility package. |
void |
dismissKeyboardShortcutsHelper()
Dismiss the Keyboard Shortcuts screen.
|
void |
dispatchEnterAnimationComplete() |
boolean |
dispatchGenericMotionEvent(MotionEvent ev)
Called to process generic motion events.
|
boolean |
dispatchKeyEvent(KeyEvent event)
Called to process key events.
|
boolean |
dispatchKeyShortcutEvent(KeyEvent event)
Called to process a key shortcut event.
|
boolean |
dispatchPopulateAccessibilityEvent(AccessibilityEvent event)
Called to process population of
AccessibilityEvent s. |
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.
|
void |
enterPictureInPictureMode()
Puts the activity in picture-in-picture mode.
|
void |
enterPictureInPictureModeIfPossible()
Puts the activity in picture-in-picture mode if the activity supports.
|
void |
exitFreeformMode()
Moves the activity from
ActivityManager.StackId.FREEFORM_WORKSPACE_STACK_ID to
ActivityManager.StackId.FULLSCREEN_WORKSPACE_STACK_ID stack. |
View |
findViewById(int id)
Finds a view that was identified by the id attribute from the XML that
was processed in
onCreate(android.os.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(android.content.Intent, int) . |
void |
finishActivityFromChild(Activity child,
int requestCode)
This is called when a child activity of this one calls its
finishActivity().
|
void |
finishAffinity()
Finish this activity as well as all activities immediately below it
in the current task that have the same affinity.
|
void |
finishAfterTransition()
Reverses the Activity Scene entry Transition and triggers the calling Activity
to reverse its exit Transition.
|
void |
finishAndRemoveTask()
Call this when your activity is done and should be closed and the task should be completely
removed as a part of finishing the root activity of the task.
|
void |
finishFromChild(Activity child)
This is called when a child activity of this one calls its
finish(int) method. |
ActionBar |
getActionBar()
Retrieve a reference to this activity's ActionBar.
|
IBinder |
getActivityToken() |
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.
|
Scene |
getContentScene()
Retrieve the
Scene representing this window's current content. |
TransitionManager |
getContentTransitionManager()
Retrieve the
TransitionManager responsible for default transitions in this window. |
View |
getCurrentFocus()
Calls
Window.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
Window.getLayoutInflater() . |
LoaderManager |
getLoaderManager()
Return the LoaderManager for this activity, creating it if needed.
|
String |
getLocalClassName()
Returns class name for this activity with the package prefix removed.
|
MediaController |
getMediaController()
Gets the controller which should be receiving media key and volume events
while this activity is in the foreground.
|
MenuInflater |
getMenuInflater()
Returns a
MenuInflater with this context. |
Activity |
getParent()
Return the parent activity if this view is an embedded child.
|
Intent |
getParentActivityIntent()
Obtain an
Intent that will launch an explicit target activity specified by
this activity's logical parent. |
SharedPreferences |
getPreferences(int mode)
Retrieve a
SharedPreferences object for accessing preferences
that are private to this activity. |
Uri |
getReferrer()
Return information about who launched this activity.
|
int |
getRequestedOrientation()
Return the current requested orientation of the activity.
|
SearchEvent |
getSearchEvent()
During the onSearchRequested() callbacks, this function will return the
SearchEvent that triggered the callback, if it exists. |
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.
|
CharSequence |
getTitle() |
int |
getTitleColor() |
VoiceInteractor |
getVoiceInteractor()
Retrieve the active
VoiceInteractor that the user is going through to
interact with this activity. |
int |
getVolumeControlStream()
Gets the suggested audio stream whose volume should be changed by the
hardware volume controls.
|
Window |
getWindow()
Retrieve the current
Window for the activity. |
WindowManager |
getWindowManager()
Retrieve the window manager for showing custom windows.
|
int |
getWindowStackId()
Returns the current stack Id for the window.
|
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 |
isBackgroundVisibleBehind()
Translucent activities may call this to determine if there is an activity below them that
is currently set to be visible in the background.
|
boolean |
isChangingConfigurations()
Check to see whether this activity is in the process of being destroyed in order to be
recreated with a new configuration.
|
boolean |
isChild()
Is this activity embedded inside of another activity?
|
boolean |
isDestroyed()
Returns true if the final
onDestroy() call has been made
on the Activity, so this instance is now dead. |
boolean |
isFinishing()
Check to see whether this activity is in the process of finishing,
either because you called
finish(int) on it or someone else
has requested that it finished. |
boolean |
isImmersive()
Bit indicating that this activity is "immersive" and should not be
interrupted by notifications if possible.
|
boolean |
isInMultiWindowMode()
Returns true if the activity is currently in multi-window mode.
|
boolean |
isInPictureInPictureMode()
Returns true if the activity is currently in picture-in-picture mode.
|
boolean |
isLocalVoiceInteractionSupported()
Queries whether the currently enabled voice interaction service supports returning
a voice interactor for use by the activity.
|
boolean |
isOverlayWithDecorCaptionEnabled()
Check whether the caption on freeform windows is displayed directly on the content.
|
boolean |
isResumed() |
boolean |
isTaskRoot()
Return whether this activity is the root of a task.
|
boolean |
isVoiceInteraction()
Check whether this activity is running as part of a voice interaction with the user.
|
boolean |
isVoiceInteractionRoot()
Like
isVoiceInteraction() , but only returns true if this is also the root
of a voice interaction. |
Cursor |
managedQuery(Uri uri,
String[] projection,
String selection,
String sortOrder)
Deprecated.
Use
CursorLoader instead. |
Cursor |
managedQuery(Uri uri,
String[] projection,
String selection,
String[] selectionArgs,
String sortOrder)
Deprecated.
Use
CursorLoader instead. |
boolean |
moveTaskToBack(boolean nonRoot)
Move the task containing this activity to the back of the activity
stack.
|
boolean |
navigateUpTo(Intent upIntent)
Navigate from this activity to the activity specified by upIntent, finishing this activity
in the process.
|
boolean |
navigateUpToFromChild(Activity child,
Intent upIntent)
This is called when a child activity of this one calls its
navigateUpTo(android.content.Intent) method. |
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 |
onActivityReenter(int resultCode,
Intent data)
Called when an activity you launched with an activity transition exposes this
Activity through a returning activity transition, giving you the resultCode
and any additional data from it.
|
protected 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.
|
protected void |
onApplyThemeResource(Resources.Theme theme,
int resid,
boolean first)
Called by
ContextThemeWrapper.setTheme(int) and ContextThemeWrapper.getTheme() to apply a theme
resource to the current Theme object. |
void |
onAttachedToWindow()
Called when the main window associated with the activity has been
attached to the window manager.
|
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 |
onBackgroundVisibleBehindChanged(boolean visible)
The topmost foreground activity will receive this call when the background visibility state
of the activity below it changes.
|
void |
onBackPressed()
Called when the activity has detected the user's press of the back
key.
|
protected void |
onChildTitleChanged(Activity childActivity,
CharSequence title) |
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).
|
protected void |
onCreate(Bundle savedInstanceState)
Called when the activity is starting.
|
void |
onCreate(Bundle savedInstanceState,
PersistableBundle persistentState)
Same as
onCreate(android.os.Bundle) but called for those activities created with
the attribute android.R.attr#persistableMode set to
persistAcrossReboots . |
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.
|
protected Dialog |
onCreateDialog(int id)
Deprecated.
Old no-arguments version of
onCreateDialog(int, Bundle) . |
protected Dialog |
onCreateDialog(int id,
Bundle args)
Deprecated.
Use the new
DialogFragment class with
FragmentManager instead; this is also
available on older platforms through the Android compatibility package. |
void |
onCreateNavigateUpTaskStack(TaskStackBuilder builder)
Define the synthetic task stack that will be generated during Up navigation from
a different task.
|
boolean |
onCreateOptionsMenu(Menu menu)
Initialize the contents of the Activity's standard options menu.
|
boolean |
onCreatePanelMenu(int featureId,
Menu menu)
Default implementation of
Window.Callback.onCreatePanelMenu(int, android.view.Menu)
for activities. |
View |
onCreatePanelView(int featureId)
Default implementation of
Window.Callback.onCreatePanelView(int)
for activities. |
boolean |
onCreateThumbnail(Bitmap outBitmap,
Canvas canvas)
Generate a new thumbnail for this activity.
|
View |
onCreateView(String name,
Context context,
AttributeSet attrs)
Standard implementation of
LayoutInflater.Factory.onCreateView(java.lang.String, android.content.Context, android.util.AttributeSet) used when
inflating with the LayoutInflater returned by getSystemService(java.lang.String) . |
View |
onCreateView(View parent,
String name,
Context context,
AttributeSet attrs)
Standard implementation of
LayoutInflater.Factory2.onCreateView(View, String, Context, AttributeSet)
used when inflating with the LayoutInflater returned by getSystemService(java.lang.String) . |
protected void |
onDestroy()
Perform any final cleanup before an activity is destroyed.
|
void |
onDetachedFromWindow()
Called when the main window associated with the activity has been
detached from the window manager.
|
void |
onEnterAnimationComplete()
Activities cannot draw during the period that their windows are animating in.
|
boolean |
onGenericMotionEvent(MotionEvent event)
Called when a generic motion event was not handled by any of the
views inside of the activity.
|
boolean |
onKeyDown(int keyCode,
KeyEvent event)
Called when a key was pressed down and not handled by any of the views
inside of the activity.
|
boolean |
onKeyLongPress(int keyCode,
KeyEvent event)
Default implementation of
KeyEvent.Callback.onKeyLongPress() : always returns false (doesn't handle
the event). |
boolean |
onKeyMultiple(int keyCode,
int repeatCount,
KeyEvent event)
Default implementation of
KeyEvent.Callback.onKeyMultiple() : always returns false (doesn't handle
the event). |
boolean |
onKeyShortcut(int keyCode,
KeyEvent event)
Called when a key shortcut event is not handled by any of the views in the Activity.
|
boolean |
onKeyUp(int keyCode,
KeyEvent event)
Called when a key was released and not handled by any of the views
inside of the activity.
|
void |
onLocalVoiceInteractionStarted()
Callback to indicate that
startLocalVoiceInteraction(Bundle) has resulted in a
voice interaction session being started. |
void |
onLocalVoiceInteractionStopped()
Callback to indicate that the local voice interaction has stopped either
because it was requested through a call to
stopLocalVoiceInteraction()
or because it was canceled by the user. |
void |
onLowMemory()
This is called when the overall system is running low on memory, and
actively running processes should trim their memory usage.
|
boolean |
onMenuItemSelected(int featureId,
MenuItem item)
Default implementation of
Window.Callback.onMenuItemSelected(int, android.view.MenuItem)
for activities. |
boolean |
onMenuOpened(int featureId,
Menu menu)
Called when a panel's menu is opened by the user.
|
void |
onMultiWindowModeChanged(boolean isInMultiWindowMode)
Called by the system when the activity changes from fullscreen mode to multi-window mode and
visa-versa.
|
boolean |
onNavigateUp()
This method is called whenever the user chooses to navigate Up within your application's
activity hierarchy from the action bar.
|
boolean |
onNavigateUpFromChild(Activity child)
This is called when a child activity of this one attempts to navigate up.
|
void |
onNewActivityOptions(ActivityOptions options) |
protected void |
onNewIntent(Intent intent)
This is called for activities that set launchMode to "singleTop" in
their package, or if a client used the
Intent.FLAG_ACTIVITY_SINGLE_TOP
flag when calling startActivity(android.content.Intent) . |
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
Window.Callback.onPanelClosed(int, Menu) for
activities. |
protected void |
onPause()
Called as part of the activity lifecycle when an activity is going into
the background, but has not (yet) been killed.
|
void |
onPictureInPictureModeChanged(boolean isInPictureInPictureMode)
Called by the system when the activity changes to and from picture-in-picture mode.
|
protected void |
onPostCreate(Bundle savedInstanceState)
Called when activity start-up is complete (after
onStart()
and onRestoreInstanceState(android.os.Bundle) have been called). |
void |
onPostCreate(Bundle savedInstanceState,
PersistableBundle persistentState)
This is the same as
onPostCreate(Bundle) but is called for activities
created with the attribute android.R.attr#persistableMode set to
persistAcrossReboots . |
protected void |
onPostResume()
Called when activity resume is complete (after
onResume() has
been called). |
protected void |
onPrepareDialog(int id,
Dialog dialog)
Deprecated.
Old no-arguments version of
onPrepareDialog(int, Dialog, Bundle) . |
protected void |
onPrepareDialog(int id,
Dialog dialog,
Bundle args)
Deprecated.
Use the new
DialogFragment class with
FragmentManager instead; this is also
available on older platforms through the Android compatibility package. |
void |
onPrepareNavigateUpTaskStack(TaskStackBuilder builder)
Prepare the synthetic task stack that will be generated during Up navigation
from a different task.
|
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
Window.Callback.onPreparePanel(int, android.view.View, android.view.Menu)
for activities. |
void |
onProvideAssistContent(AssistContent outContent)
This is called when the user is requesting an assist, to provide references
to content related to the current activity.
|
void |
onProvideAssistData(Bundle data)
This is called when the user is requesting an assist, to build a full
Intent.ACTION_ASSIST Intent with all of the context of the current
application. |
void |
onProvideKeyboardShortcuts(List<KeyboardShortcutGroup> data,
Menu menu,
int deviceId)
Called when Keyboard Shortcuts are requested for the current window.
|
Uri |
onProvideReferrer()
Override to generate the desired referrer for the content currently being shown
by the app.
|
void |
onRequestPermissionsResult(int requestCode,
String[] permissions,
int[] grantResults)
Callback for the result from requesting permissions.
|
protected void |
onRestart()
Called after
onStop() when the current activity is being
re-displayed to the user (the user has navigated back to it). |
protected 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 |
onRestoreInstanceState(Bundle savedInstanceState,
PersistableBundle persistentState)
This is the same as
onRestoreInstanceState(Bundle) but is called for activities
created with the attribute android.R.attr#persistableMode set to
persistAcrossReboots . |
protected void |
onResume()
Called after
onRestoreInstanceState(android.os.Bundle) , onRestart() , or
onPause() , for your activity to start interacting with the user. |
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.
|
protected 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(android.os.Bundle) or
onRestoreInstanceState(android.os.Bundle) (the Bundle populated by this method
will be passed to both). |
void |
onSaveInstanceState(Bundle outState,
PersistableBundle outPersistentState)
This is the same as
onSaveInstanceState(android.os.Bundle) but is called for activities
created with the attribute android.R.attr#persistableMode set to
persistAcrossReboots . |
boolean |
onSearchRequested()
Called when the user signals the desire to start a search.
|
boolean |
onSearchRequested(SearchEvent searchEvent)
This hook is called when the user signals the desire to start a search.
|
protected void |
onStart()
Called after
onCreate(android.os.Bundle) — or after onRestart() when
the activity had been stopped, but is now again being displayed to the
user. |
void |
onStateNotSaved()
Called when an
onResume() is coming up, prior to other pre-resume callbacks
such as onNewIntent(android.content.Intent) and onActivityResult(int, int, android.content.Intent) . |
protected void |
onStop()
Called when you are no longer visible to the user.
|
protected void |
onTitleChanged(CharSequence title,
int color) |
boolean |
onTouchEvent(MotionEvent event)
Called when a touch screen event was not handled by any of the views
under it.
|
boolean |
onTrackballEvent(MotionEvent event)
Called when the trackball was moved and not handled by any of the
views inside of the activity.
|
void |
onTrimMemory(int level)
Called when the operating system has determined that it is a good
time for a process to trim unneeded memory from its process.
|
void |
onUserInteraction()
Called whenever a key, touch, or trackball event is dispatched to the
activity.
|
protected 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.
|
void |
onVisibleBehindCanceled()
Called when a translucent activity over this activity is becoming opaque or another
activity is being launched.
|
void |
onWindowAttributesChanged(WindowManager.LayoutParams params)
This is called whenever the current window attributes change.
|
void |
onWindowDismissed(boolean finishTask)
Called when the main window associated with the activity has been dismissed.
|
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.
|
ActionMode |
onWindowStartingActionMode(ActionMode.Callback callback,
int type)
Called when an action mode is being started for this window.
|
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(int) to specify an explicit transition animation to
perform next. |
void |
postponeEnterTransition()
Postpone the entering activity transition when Activity was started with
ActivityOptions.makeSceneTransitionAnimation(Activity,
android.util.Pair[]) . |
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).
|
boolean |
releaseInstance()
Ask that the local app instance of this activity be released to free up its memory.
|
void |
removeDialog(int id)
Deprecated.
Use the new
DialogFragment class with
FragmentManager instead; this is also
available on older platforms through the Android compatibility package. |
void |
reportFullyDrawn()
Report to the system that your app is now fully drawn, purely for diagnostic
purposes (calling it does not impact the visible behavior of the activity).
|
DragAndDropPermissions |
requestDragAndDropPermissions(DragEvent event)
Create
DragAndDropPermissions object bound to this activity and controlling the
access permissions for content URIs associated with the DragEvent . |
void |
requestPermissions(String[] permissions,
int requestCode)
Requests permissions to be granted to this application.
|
void |
requestShowKeyboardShortcuts()
Request the Keyboard Shortcuts screen to show up.
|
boolean |
requestVisibleBehind(boolean visible)
Activities that want to remain visible behind a translucent activity above them must call
this method anytime between the start of
onResume() and the return from
onPause() . |
boolean |
requestWindowFeature(int featureId)
Enable extended window features.
|
void |
runOnUiThread(Runnable action)
Runs the specified action on the UI thread.
|
void |
setActionBar(Toolbar toolbar)
|
void |
setContentTransitionManager(TransitionManager tm)
Set the
TransitionManager to use for default transitions in this window. |
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.
|
void |
setDefaultKeyMode(int mode)
Select the default key handling for this activity.
|
void |
setEnterSharedElementCallback(SharedElementCallback callback)
When
ActivityOptions.makeSceneTransitionAnimation(Activity,
android.view.View, String) was used to start an Activity, callback
will be called to handle shared elements on the launched Activity. |
void |
setExitSharedElementCallback(SharedElementCallback callback)
When
ActivityOptions.makeSceneTransitionAnimation(Activity,
android.view.View, String) was used to start an Activity, callback
will be called to handle shared elements on the launching Activity. |
void |
setFeatureDrawable(int featureId,
Drawable drawable)
Convenience for calling
Window.setFeatureDrawable(int, Drawable) . |
void |
setFeatureDrawableAlpha(int featureId,
int alpha)
Convenience for calling
Window.setFeatureDrawableAlpha(int, int) . |
void |
setFeatureDrawableResource(int featureId,
int resId)
Convenience for calling
Window.setFeatureDrawableResource(int, int) . |
void |
setFeatureDrawableUri(int featureId,
Uri uri)
Convenience for calling
Window.setFeatureDrawableUri(int, android.net.Uri) . |
void |
setFinishOnTouchOutside(boolean finish)
Sets whether this activity is finished when touched outside its window's
bounds.
|
void |
setImmersive(boolean i)
Adjust the current immersive mode setting.
|
void |
setIntent(Intent newIntent)
Change the intent returned by
getIntent() . |
void |
setMediaController(MediaController controller)
Sets a
MediaController to send media keys and volume changes to. |
void |
setOverlayWithDecorCaptionEnabled(boolean enabled)
Set whether the caption should displayed directly on the content rather than push it down.
|
void |
setPersistent(boolean isPersistent)
Deprecated.
As of
Build.VERSION_CODES.GINGERBREAD
this is a no-op. |
void |
setProgress(int progress)
Deprecated.
No longer supported starting in API 21.
|
void |
setProgressBarIndeterminate(boolean indeterminate)
Deprecated.
No longer supported starting in API 21.
|
void |
setProgressBarIndeterminateVisibility(boolean visible)
Deprecated.
No longer supported starting in API 21.
|
void |
setProgressBarVisibility(boolean visible)
Deprecated.
No longer supported starting in API 21.
|
void |
setRequestedOrientation(int requestedOrientation)
Change the desired orientation of this activity.
|
void |
setResult(int resultCode)
Call this to set the result that your activity will return to its
caller.
|
void |
setResult(int resultCode,
Intent data)
Call this to set the result that your activity will return to its
caller.
|
void |
setSecondaryProgress(int secondaryProgress)
Deprecated.
No longer supported starting in API 21.
|
void |
setTaskDescription(ActivityManager.TaskDescription taskDescription)
Sets information describing the task with this activity for presentation inside the Recents
System UI.
|
void |
setTheme(int resid)
Set the base theme for this context.
|
void |
setTitle(CharSequence title)
Change the title associated with this activity.
|
void |
setTitle(int titleId)
Change the title associated with this activity.
|
void |
setTitleColor(int textColor)
Deprecated.
Use action bar styles instead.
|
void |
setVisible(boolean visible)
Control whether this activity's main window is visible.
|
void |
setVolumeControlStream(int streamType)
Suggests an audio stream whose volume should be changed by the hardware
volume controls.
|
void |
setVrModeEnabled(boolean enabled,
ComponentName requestedComponent)
Enable or disable virtual reality (VR) mode for this Activity.
|
boolean |
shouldShowRequestPermissionRationale(String permission)
Gets whether you should show UI with rationale for requesting a permission.
|
boolean |
shouldUpRecreateTask(Intent targetIntent)
Returns true if the app should recreate the task when navigating 'up' from this activity
by using targetIntent.
|
boolean |
showAssist(Bundle args)
Ask to have the current assistant shown to the user.
|
void |
showDialog(int id)
Deprecated.
Use the new
DialogFragment class with
FragmentManager instead; this is also
available on older platforms through the Android compatibility package. |
boolean |
showDialog(int id,
Bundle args)
Deprecated.
Use the new
DialogFragment class with
FragmentManager instead; this is also
available on older platforms through the Android compatibility package. |
void |
showLockTaskEscapeMessage()
Shows the user the system defined message for telling the user how to exit
lock task mode.
|
ActionMode |
startActionMode(ActionMode.Callback callback)
Start an action mode of the default type
ActionMode.TYPE_PRIMARY . |
ActionMode |
startActionMode(ActionMode.Callback callback,
int type)
Start an action mode of the given type.
|
void |
startActivities(Intent[] intents)
Same as
startActivities(Intent[], Bundle) with no options
specified. |
void |
startActivities(Intent[] intents,
Bundle options)
Launch a new activity.
|
void |
startActivity(Intent intent)
Same as
startActivity(Intent, Bundle) with no options
specified. |
void |
startActivity(Intent intent,
Bundle options)
Launch a new activity.
|
void |
startActivityAsCaller(Intent intent,
Bundle options,
boolean ignoreTargetSecurity,
int userId)
Start a new activity as if it was started by the activity that started our
current activity.
|
void |
startActivityAsUser(Intent intent,
Bundle options,
UserHandle user)
Version of
Context.startActivity(Intent, Bundle) that allows you to specify the
user the activity will be started for. |
void |
startActivityAsUser(Intent intent,
UserHandle user)
Version of
Context.startActivity(Intent) that allows you to specify the
user the activity will be started for. |
void |
startActivityForResult(Intent intent,
int requestCode)
Same as calling
startActivityForResult(Intent, int, Bundle)
with no options. |
void |
startActivityForResult(Intent intent,
int requestCode,
Bundle options)
Launch an activity for which you would like a result when it finished.
|
void |
startActivityForResult(String who,
Intent intent,
int requestCode,
Bundle options)
Version of
Context.startActivity(Intent, Bundle) that returns a result to the caller. |
void |
startActivityForResultAsUser(Intent intent,
int requestCode,
Bundle options,
UserHandle user) |
void |
startActivityForResultAsUser(Intent intent,
int requestCode,
UserHandle user) |
void |
startActivityFromChild(Activity child,
Intent intent,
int requestCode)
Same as calling
startActivityFromChild(Activity, Intent, int, Bundle)
with no options. |
void |
startActivityFromChild(Activity child,
Intent intent,
int requestCode,
Bundle options)
This is called when a child activity of this one calls its
startActivity(android.content.Intent) or startActivityForResult(android.content.Intent, int) method. |
void |
startActivityFromFragment(Fragment fragment,
Intent intent,
int requestCode)
Same as calling
startActivityFromFragment(Fragment, Intent, int, Bundle)
with no options. |
void |
startActivityFromFragment(Fragment fragment,
Intent intent,
int requestCode,
Bundle options)
This is called when a Fragment in this activity calls its
Fragment.startActivity(android.content.Intent) or Fragment.startActivityForResult(android.content.Intent, int)
method. |
boolean |
startActivityIfNeeded(Intent intent,
int requestCode)
Same as calling
startActivityIfNeeded(Intent, int, Bundle)
with no options. |
boolean |
startActivityIfNeeded(Intent intent,
int requestCode,
Bundle options)
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)
Same as calling
startIntentSender(IntentSender, Intent, int, int, int, Bundle)
with no options. |
void |
startIntentSender(IntentSender intent,
Intent fillInIntent,
int flagsMask,
int flagsValues,
int extraFlags,
Bundle options)
Like
startActivity(Intent, Bundle) , but taking a IntentSender
to start; see
startIntentSenderForResult(IntentSender, int, Intent, int, int, int, Bundle)
for more information. |
void |
startIntentSenderForResult(IntentSender intent,
int requestCode,
Intent fillInIntent,
int flagsMask,
int flagsValues,
int extraFlags)
Same as calling
startIntentSenderForResult(IntentSender, int,
Intent, int, int, int, Bundle) with no options. |
void |
startIntentSenderForResult(IntentSender intent,
int requestCode,
Intent fillInIntent,
int flagsMask,
int flagsValues,
int extraFlags,
Bundle options)
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)
Same as calling
startIntentSenderFromChild(Activity, IntentSender,
int, Intent, int, int, int, Bundle) with no options. |
void |
startIntentSenderFromChild(Activity child,
IntentSender intent,
int requestCode,
Intent fillInIntent,
int flagsMask,
int flagsValues,
int extraFlags,
Bundle options)
Like
startActivityFromChild(Activity, Intent, int) , but
taking a IntentSender; see
startIntentSenderForResult(IntentSender, int, Intent, int, int, int)
for more information. |
void |
startIntentSenderFromChildFragment(Fragment child,
IntentSender intent,
int requestCode,
Intent fillInIntent,
int flagsMask,
int flagsValues,
int extraFlags,
Bundle options)
Like
startIntentSenderFromChild(android.app.Activity, android.content.IntentSender, int, android.content.Intent, int, int, int) , but taking a Fragment; see
startIntentSenderForResult(IntentSender, int, Intent, int, int, int)
for more information. |
void |
startLocalVoiceInteraction(Bundle privateOptions)
Starts a local voice interaction session.
|
void |
startLockTask()
Request to put this Activity in a mode where the user is locked to the
current task.
|
void |
startManagingCursor(Cursor c)
Deprecated.
Use the new
CursorLoader class with
LoaderManager instead; this is also
available on older platforms through the Android compatibility package. |
boolean |
startNextMatchingActivity(Intent intent)
Same as calling
startNextMatchingActivity(Intent, Bundle) with
no options. |
boolean |
startNextMatchingActivity(Intent intent,
Bundle options)
Special version of starting an activity, for use when you are replacing
other activity components.
|
void |
startPostponedEnterTransition()
Begin postponed transitions after
postponeEnterTransition() was called. |
void |
startSearch(String initialQuery,
boolean selectInitialQuery,
Bundle appSearchData,
boolean globalSearch)
This hook is called to launch the search UI.
|
void |
stopLocalVoiceInteraction()
Request to terminate the current voice interaction that was previously started
using
startLocalVoiceInteraction(Bundle) . |
void |
stopLockTask()
Allow the user to switch away from the current task.
|
void |
stopManagingCursor(Cursor c)
Deprecated.
Use the new
CursorLoader class with
LoaderManager instead; this is also
available on older platforms through the Android compatibility package. |
void |
takeKeyEvents(boolean get)
Request that key events come to this activity.
|
void |
triggerSearch(String query,
Bundle appSearchData)
Similar to
startSearch(java.lang.String, boolean, android.os.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.
|
applyOverrideConfiguration, attachBaseContext, getAssets, getOverrideConfiguration, getResources, getTheme, getThemeResId
bindService, bindServiceAsUser, checkCallingOrSelfPermission, checkCallingOrSelfUriPermission, checkCallingPermission, checkCallingUriPermission, checkPermission, checkPermission, checkSelfPermission, checkUriPermission, checkUriPermission, checkUriPermission, clearWallpaper, createApplicationContext, createConfigurationContext, createCredentialProtectedStorageContext, createDeviceProtectedStorageContext, createDisplayContext, createPackageContext, createPackageContextAsUser, databaseList, deleteDatabase, deleteFile, deleteSharedPreferences, enforceCallingOrSelfPermission, enforceCallingOrSelfUriPermission, enforceCallingPermission, enforceCallingUriPermission, enforcePermission, enforceUriPermission, enforceUriPermission, fileList, getApplicationContext, getApplicationInfo, getBaseContext, getBasePackageName, getCacheDir, getClassLoader, getCodeCacheDir, getContentResolver, getDatabasePath, getDataDir, getDir, getDisplay, getDisplayAdjustments, getExternalCacheDir, getExternalCacheDirs, getExternalFilesDir, getExternalFilesDirs, getExternalMediaDirs, getFilesDir, getFileStreamPath, getMainLooper, getNoBackupFilesDir, getObbDir, getObbDirs, getOpPackageName, getPackageCodePath, getPackageManager, getPackageName, getPackageResourcePath, getSharedPreferences, getSharedPreferences, getSharedPreferencesPath, getSystemServiceName, getUserId, getWallpaper, getWallpaperDesiredMinimumHeight, getWallpaperDesiredMinimumWidth, grantUriPermission, isCredentialProtectedStorage, isDeviceProtectedStorage, isRestricted, moveDatabaseFrom, moveSharedPreferencesFrom, openFileInput, openFileOutput, openOrCreateDatabase, openOrCreateDatabase, peekWallpaper, registerReceiver, registerReceiver, registerReceiverAsUser, removeStickyBroadcast, removeStickyBroadcastAsUser, revokeUriPermission, sendBroadcast, sendBroadcast, sendBroadcast, sendBroadcast, sendBroadcastAsUser, sendBroadcastAsUser, sendBroadcastAsUser, sendBroadcastMultiplePermissions, sendOrderedBroadcast, sendOrderedBroadcast, sendOrderedBroadcast, sendOrderedBroadcast, sendOrderedBroadcastAsUser, sendOrderedBroadcastAsUser, sendOrderedBroadcastAsUser, sendStickyBroadcast, sendStickyBroadcastAsUser, sendStickyBroadcastAsUser, sendStickyOrderedBroadcast, sendStickyOrderedBroadcastAsUser, setWallpaper, setWallpaper, startActivitiesAsUser, startInstrumentation, startService, startServiceAsUser, stopService, stopServiceAsUser, unbindService, unregisterReceiver
bindServiceAsUser, createCredentialEncryptedStorageContext, createDeviceEncryptedStorageContext, getColor, getColorStateList, getDrawable, getSharedPrefsFile, getString, getString, getSystemService, getText, isCredentialEncryptedStorage, isDeviceEncryptedStorage, migrateDatabaseFrom, migrateSharedPreferencesFrom, obtainStyledAttributes, obtainStyledAttributes, obtainStyledAttributes, obtainStyledAttributes, registerComponentCallbacks, unregisterComponentCallbacks
public static final int RESULT_CANCELED
public static final int RESULT_OK
public static final int RESULT_FIRST_USER
public static final int DONT_FINISH_TASK_WITH_ACTIVITY
public static final int FINISH_TASK_WITH_ROOT_ACTIVITY
public static final int FINISH_TASK_WITH_ACTIVITY
protected static final int[] FOCUSED_STATE_SET
public static final int DEFAULT_KEYS_DISABLE
setDefaultKeyMode(int)
to turn off default handling of
keys.setDefaultKeyMode(int)
,
Constant Field Valuespublic static final int DEFAULT_KEYS_DIALER
setDefaultKeyMode(int)
to launch the dialer during default
key handling.setDefaultKeyMode(int)
,
Constant Field Valuespublic static final int DEFAULT_KEYS_SHORTCUT
setDefaultKeyMode(int)
to execute a menu shortcut in
default key handling.
That is, the user does not need to hold down the menu key to execute menu shortcuts.
setDefaultKeyMode(int)
,
Constant Field Valuespublic static final int DEFAULT_KEYS_SEARCH_LOCAL
setDefaultKeyMode(int)
to specify that unhandled keystrokes
will start an application-defined search. (If the application or activity does not
actually define a search, the the keys will be ignored.)
See android.app.SearchManager
for more details.
setDefaultKeyMode(int)
,
Constant Field Valuespublic static final int DEFAULT_KEYS_SEARCH_GLOBAL
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.
setDefaultKeyMode(int)
,
Constant Field Valuespublic Intent getIntent()
public void setIntent(Intent newIntent)
getIntent()
. This holds a
reference to the given intent; it does not copy it. Often used in
conjunction with onNewIntent(android.content.Intent)
.newIntent
- The new Intent object to return from getIntentgetIntent()
,
onNewIntent(android.content.Intent)
public final Application getApplication()
public final boolean isChild()
public final Activity getParent()
public WindowManager getWindowManager()
public Window getWindow()
Window
for the activity.
This can be used to directly access parts of the Window API that
are not available through Activity/Screen.public LoaderManager getLoaderManager()
public View getCurrentFocus()
Window.getCurrentFocus()
on the
Window of this Activity to return the currently focused view.getWindow()
,
Window.getCurrentFocus()
protected void onCreate(Bundle savedInstanceState)
setContentView(int)
to inflate the
activity's UI, using findViewById(int)
to programmatically interact
with widgets in the UI, calling
managedQuery(android.net.Uri , String[], String, String[], String)
to retrieve
cursors for data being displayed, etc.
You can call finish(int)
from within this function, in
which case onDestroy() will be immediately called without any of the rest
of the activity lifecycle (onStart()
, onResume()
,
onPause()
, etc) executing.
Derived classes must call through to the super class's implementation of this method. If they do not, an exception will be thrown.
savedInstanceState
- If the activity is being re-initialized after
previously being shut down then this Bundle contains the data it most
recently supplied in onSaveInstanceState(android.os.Bundle)
. Note: Otherwise it is null.onStart()
,
onSaveInstanceState(android.os.Bundle)
,
onRestoreInstanceState(android.os.Bundle)
,
onPostCreate(android.os.Bundle)
public void onCreate(Bundle savedInstanceState, PersistableBundle persistentState)
onCreate(android.os.Bundle)
but called for those activities created with
the attribute android.R.attr#persistableMode
set to
persistAcrossReboots
.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(android.os.Bundle)
.
Note: Otherwise it is null.persistentState
- if the activity is being re-initialized after
previously being shut down or powered off then this Bundle contains the data it most
recently supplied to outPersistentState in onSaveInstanceState(android.os.Bundle)
.
Note: Otherwise it is null.onCreate(android.os.Bundle)
,
onStart()
,
onSaveInstanceState(android.os.Bundle)
,
onRestoreInstanceState(android.os.Bundle)
,
onPostCreate(android.os.Bundle)
protected void onRestoreInstanceState(Bundle savedInstanceState)
onStart()
when the activity is
being re-initialized from a previously saved state, given here in
savedInstanceState. Most implementations will simply use onCreate(android.os.Bundle)
to restore their state, but it is sometimes convenient to do it here
after all of the initialization has been done or to allow subclasses to
decide whether to use your default implementation. The default
implementation of this method performs a restore of any view state that
had previously been frozen by onSaveInstanceState(android.os.Bundle)
.
This method is called between onStart()
and
onPostCreate(android.os.Bundle)
.
savedInstanceState
- the data most recently supplied in onSaveInstanceState(android.os.Bundle)
.onCreate(android.os.Bundle)
,
onPostCreate(android.os.Bundle)
,
onResume()
,
onSaveInstanceState(android.os.Bundle)
public void onRestoreInstanceState(Bundle savedInstanceState, PersistableBundle persistentState)
onRestoreInstanceState(Bundle)
but is called for activities
created with the attribute android.R.attr#persistableMode
set to
persistAcrossReboots
. The PersistableBundle
passed
came from the restored PersistableBundle first
saved in onSaveInstanceState(Bundle, PersistableBundle)
.
This method is called between onStart()
and
onPostCreate(android.os.Bundle)
.
If this method is called onRestoreInstanceState(Bundle)
will not be called.
savedInstanceState
- the data most recently supplied in onSaveInstanceState(android.os.Bundle)
.persistentState
- the data most recently supplied in onSaveInstanceState(android.os.Bundle)
.onRestoreInstanceState(Bundle)
,
onCreate(android.os.Bundle)
,
onPostCreate(android.os.Bundle)
,
onResume()
,
onSaveInstanceState(android.os.Bundle)
protected void onPostCreate(Bundle savedInstanceState)
onStart()
and onRestoreInstanceState(android.os.Bundle)
have been called). Applications will
generally not implement this method; it is intended for system
classes to do final initialization after application code has run.
Derived classes must call through to the super class's implementation of this method. If they do not, an exception will be thrown.
savedInstanceState
- If the activity is being re-initialized after
previously being shut down then this Bundle contains the data it most
recently supplied in onSaveInstanceState(android.os.Bundle)
. Note: Otherwise it is null.onCreate(android.os.Bundle)
public void onPostCreate(Bundle savedInstanceState, PersistableBundle persistentState)
onPostCreate(Bundle)
but is called for activities
created with the attribute android.R.attr#persistableMode
set to
persistAcrossReboots
.savedInstanceState
- The data most recently supplied in onSaveInstanceState(android.os.Bundle)
persistentState
- The data caming from the PersistableBundle first
saved in onSaveInstanceState(Bundle, PersistableBundle)
.onCreate(android.os.Bundle)
protected void onStart()
onCreate(android.os.Bundle)
— or after onRestart()
when
the activity had been stopped, but is now again being displayed to the
user. It will be followed by onResume()
.
Derived classes must call through to the super class's implementation of this method. If they do not, an exception will be thrown.
onCreate(android.os.Bundle)
,
onStop()
,
onResume()
protected void onRestart()
onStop()
when the current activity is being
re-displayed to the user (the user has navigated back to it). It will
be followed by onStart()
and then onResume()
.
For activities that are using raw Cursor
objects (instead of
creating them through
managedQuery(android.net.Uri , String[], String, String[], String)
,
this is usually the place
where the cursor should be requeried (because you had deactivated it in
onStop()
.
Derived classes must call through to the super class's implementation of this method. If they do not, an exception will be thrown.
onStop()
,
onStart()
,
onResume()
public void onStateNotSaved()
onResume()
is coming up, prior to other pre-resume callbacks
such as onNewIntent(android.content.Intent)
and onActivityResult(int, int, android.content.Intent)
. This is primarily intended
to give the activity a hint that its state is no longer saved -- it will generally
be called after onSaveInstanceState(android.os.Bundle)
and prior to the activity being
resumed/started again.protected void onResume()
onRestoreInstanceState(android.os.Bundle)
, onRestart()
, or
onPause()
, for your activity to start interacting with the user.
This is a good place to begin animations, open exclusive-access devices
(such as the camera), etc.
Keep in mind that onResume is not the best indicator that your activity
is visible to the user; a system window such as the keyguard may be in
front. Use onWindowFocusChanged(boolean)
to know for certain that your
activity is visible to the user (for example, to resume a game).
Derived classes must call through to the super class's implementation of this method. If they do not, an exception will be thrown.
protected void onPostResume()
onResume()
has
been called). Applications will generally not implement this method;
it is intended for system classes to do final setup after application
resume code has run.
Derived classes must call through to the super class's implementation of this method. If they do not, an exception will be thrown.
onResume()
public boolean isVoiceInteraction()
VoiceInteractor
returned by getVoiceInteractor()
.public boolean isVoiceInteractionRoot()
isVoiceInteraction()
, but only returns true if this is also the root
of a voice interaction. That is, returns true if this activity was directly
started by the voice interaction service as the initiation of a voice interaction.
Otherwise, for example if it was started by another activity while under voice
interaction, returns false.public VoiceInteractor getVoiceInteractor()
VoiceInteractor
that the user is going through to
interact with this activity.public boolean isLocalVoiceInteractionSupported()
public void startLocalVoiceInteraction(Bundle privateOptions)
onLocalVoiceInteractionStarted()
is called. You can pass a bundle of private options
to the registered voice interaction service.privateOptions
- a Bundle of private arguments to the current voice interaction servicepublic void onLocalVoiceInteractionStarted()
startLocalVoiceInteraction(Bundle)
has resulted in a
voice interaction session being started. You can now retrieve a voice interactor using
getVoiceInteractor()
.public void onLocalVoiceInteractionStopped()
stopLocalVoiceInteraction()
or because it was canceled by the user. The previously acquired VoiceInteractor
is no longer valid after this.public void stopLocalVoiceInteraction()
startLocalVoiceInteraction(Bundle)
. When the interaction is
terminated, onLocalVoiceInteractionStopped()
will be called.protected void onNewIntent(Intent intent)
Intent.FLAG_ACTIVITY_SINGLE_TOP
flag when calling startActivity(android.content.Intent)
. In either case, when the
activity is re-launched while at the top of the activity stack instead
of a new instance of the activity being started, onNewIntent() will be
called on the existing instance with the Intent that was used to
re-launch it.
An activity will always be paused before receiving a new intent, so
you can count on onResume()
being called after this method.
Note that getIntent()
still returns the original Intent. You
can use setIntent(android.content.Intent)
to update it to this new Intent.
intent
- The new intent that was started for the activity.getIntent()
,
setIntent(android.content.Intent)
,
onResume()
protected void onSaveInstanceState(Bundle outState)
onCreate(android.os.Bundle)
or
onRestoreInstanceState(android.os.Bundle)
(the Bundle
populated by this method
will be passed to both).
This method is called before an activity may be killed so that when it
comes back some time in the future it can restore its state. For example,
if activity B is launched in front of activity A, and at some point activity
A is killed to reclaim resources, activity A will have a chance to save the
current state of its user interface via this method so that when the user
returns to activity A, the state of the user interface can be restored
via onCreate(android.os.Bundle)
or onRestoreInstanceState(android.os.Bundle)
.
Do not confuse this method with activity lifecycle callbacks such as
onPause()
, which is always called when an activity is being placed
in the background or on its way to destruction, or onStop()
which
is called before destruction. One example of when onPause()
and
onStop()
is called and not this method is when a user navigates back
from activity B to activity A: there is no need to call onSaveInstanceState(android.os.Bundle)
on B because that particular instance will never be restored, so the
system avoids calling it. An example when onPause()
is called and
not onSaveInstanceState(android.os.Bundle)
is when activity B is launched in front of activity A:
the system may avoid calling onSaveInstanceState(android.os.Bundle)
on activity A if it isn't
killed during the lifetime of B since the state of the user interface of
A will stay intact.
The default implementation takes care of most of the UI per-instance
state for you by calling View.onSaveInstanceState()
on each
view in the hierarchy that has an id, and by saving the id of the currently
focused view (all of which is restored by the default implementation of
onRestoreInstanceState(android.os.Bundle)
). If you override this method to save additional
information not captured by each individual view, you will likely want to
call through to the default implementation, otherwise be prepared to save
all of the state of each view yourself.
If called, this method will occur before onStop()
. There are
no guarantees about whether it will occur before or after onPause()
.
outState
- Bundle in which to place your saved state.onCreate(android.os.Bundle)
,
onRestoreInstanceState(android.os.Bundle)
,
onPause()
public void onSaveInstanceState(Bundle outState, PersistableBundle outPersistentState)
onSaveInstanceState(android.os.Bundle)
but is called for activities
created with the attribute android.R.attr#persistableMode
set to
persistAcrossReboots
. The PersistableBundle
passed
in will be saved and presented in onCreate(Bundle, PersistableBundle)
the first time that this activity is restarted following the next device reboot.outState
- Bundle in which to place your saved state.outPersistentState
- State which will be saved across reboots.onSaveInstanceState(Bundle)
,
onCreate(android.os.Bundle)
,
onRestoreInstanceState(Bundle, PersistableBundle)
,
onPause()
protected void onPause()
onResume()
.
When activity B is launched in front of activity A, this callback will
be invoked on A. B will not be created until A's onPause()
returns,
so be sure to not do anything lengthy here.
This callback is mostly used for saving any persistent state the activity is editing, to present a "edit in place" model to the user and making sure nothing is lost if there are not enough resources to start the new activity without first killing this one. This is also a good place to do things like stop animations and other things that consume a noticeable amount of CPU in order to make the switch to the next activity as fast as possible, or to close resources that are exclusive access such as the camera.
In situations where the system needs more memory it may kill paused
processes to reclaim resources. Because of this, you should be sure
that all of your state is saved by the time you return from
this function. In general onSaveInstanceState(android.os.Bundle)
is used to save
per-instance state in the activity and this method is used to store
global persistent data (in content providers, files, etc.)
After receiving this call you will usually receive a following call
to onStop()
(after the next activity has been resumed and
displayed), however in some cases there will be a direct call back to
onResume()
without going through the stopped state.
Derived classes must call through to the super class's implementation of this method. If they do not, an exception will be thrown.
onResume()
,
onSaveInstanceState(android.os.Bundle)
,
onStop()
protected void onUserLeaveHint()
onUserLeaveHint()
will be called, but
when an incoming phone call causes the in-call Activity to be automatically
brought to the foreground, onUserLeaveHint()
will not be called on
the activity being interrupted. In cases when it is invoked, this method
is called right before the activity's onPause()
callback.
This callback and onUserInteraction()
are intended to help
activities manage status bar notifications intelligently; specifically,
for helping activities determine the proper time to cancel a notfication.
onUserInteraction()
public boolean onCreateThumbnail(Bitmap outBitmap, Canvas canvas)
The default implementation returns fails and does not draw a thumbnail; this will result in the platform creating its own thumbnail if needed.
outBitmap
- The bitmap to contain the thumbnail.canvas
- Can be used to render into the bitmap.onCreateDescription()
,
onSaveInstanceState(android.os.Bundle)
,
onPause()
public CharSequence onCreateDescription()
The default implementation returns null, which will cause you to inherit the description from the previous activity. If all activities return null, generally the label of the top activity will be used as the description.
onCreateThumbnail(android.graphics.Bitmap, android.graphics.Canvas)
,
onSaveInstanceState(android.os.Bundle)
,
onPause()
public void onProvideAssistData(Bundle data)
Intent.ACTION_ASSIST
Intent with all of the context of the current
application. You can override this method to place into the bundle anything
you would like to appear in the Intent.EXTRA_ASSIST_CONTEXT
part
of the assist Intent.
This function will be called after any global assist callbacks that had
been registered with Application.registerOnProvideAssistDataListener
.
public void onProvideAssistContent(AssistContent outContent)
outContent
Intent is filled with the base Intent of the activity (the Intent
returned by getIntent()
). The Intent's extras are stripped of any types
that are not valid for PersistableBundle
or non-framework Parcelables, and
the flags Intent.FLAG_GRANT_WRITE_URI_PERMISSION
and
Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION
are cleared from the Intent.
Custom implementation may adjust the content intent to better reflect the top-level context of the activity, and fill in its ClipData with additional content of interest that the user is currently viewing. For example, an image gallery application that has launched in to an activity allowing the user to swipe through pictures should modify the intent to reference the current image they are looking it; such an application when showing a list of pictures should add a ClipData that has references to all of the pictures currently visible on screen.
outContent
- The assist content to return.public final void requestShowKeyboardShortcuts()
onProvideKeyboardShortcuts(java.util.List<android.view.KeyboardShortcutGroup>, android.view.Menu, int)
to retrieve the shortcuts for the foreground activity.public final void dismissKeyboardShortcutsHelper()
public void onProvideKeyboardShortcuts(List<KeyboardShortcutGroup> data, Menu menu, int deviceId)
Window.Callback
onProvideKeyboardShortcuts
in interface Window.Callback
data
- The data list to populate with shortcuts.menu
- The current menu, which may be null.deviceId
- The id for the connected device the shortcuts should be provided for.public boolean showAssist(Bundle args)
VoiceInteractionService.showSession
and requesting all of the possible context.
The receiver will always see
VoiceInteractionSession.SHOW_SOURCE_APPLICATION
set.protected void onStop()
onRestart()
, onDestroy()
, or nothing,
depending on later user activity.
Derived classes must call through to the super class's implementation of this method. If they do not, an exception will be thrown.
protected void onDestroy()
finish(int)
on it, or because the system is temporarily destroying
this instance of the activity to save space. You can distinguish
between these two scenarios with the isFinishing()
method.
Note: do not count on this method being called as a place for
saving data! For example, if an activity is editing data in a content
provider, those edits should be committed in either onPause()
or
onSaveInstanceState(android.os.Bundle)
, not here. This method is usually implemented to
free resources like threads that are associated with an activity, so
that a destroyed activity does not leave such things around while the
rest of its application is still running. There are situations where
the system will simply kill the activity's hosting process without
calling this method (or any others) in it, so it should not be used to
do things that are intended to remain around after the process goes
away.
Derived classes must call through to the super class's implementation of this method. If they do not, an exception will be thrown.
onPause()
,
onStop()
,
finish(int)
,
isFinishing()
public void reportFullyDrawn()
onCreate(android.os.Bundle)
is called), at the point where you have
entirely drawn your UI and populated with all of the significant data. You
can safely call this method any time after first launch as well, in which case
it will simply be ignored.public void onMultiWindowModeChanged(boolean isInMultiWindowMode)
isInMultiWindowMode
- True if the activity is in multi-window mode.android.R.attr#resizeableActivity
public boolean isInMultiWindowMode()
android.R.attr#resizeableActivity
public void onPictureInPictureModeChanged(boolean isInPictureInPictureMode)
isInPictureInPictureMode
- True if the activity is in picture-in-picture mode.android.R.attr#supportsPictureInPicture
public boolean isInPictureInPictureMode()
android.R.attr#supportsPictureInPicture
public void enterPictureInPictureMode()
android.R.attr#supportsPictureInPicture
public void onConfigurationChanged(Configuration newConfig)
android.R.attr#configChanges
attribute in your manifest. If
any configuration change occurs that is not selected to be reported
by that attribute, then instead of reporting it the system will stop
and restart the activity (to have it launched with the new
configuration).
At the time that this function has been called, your Resources object will have been updated to return resource values matching the new configuration.
onConfigurationChanged
in interface ComponentCallbacks
newConfig
- The new device configuration.public int getChangingConfigurations()
onConfigurationChanged(Configuration)
method is
not being called), then you can use this method to discover
the set of changes that have occurred while in the process of being
destroyed. Note that there is no guarantee that these will be
accurate (other changes could have happened at any time), so you should
only use this as an optimization hint.Configuration
class.public Object getLastNonConfigurationInstance()
onRetainNonConfigurationInstance()
. This will
be available from the initial onCreate(android.os.Bundle)
and
onStart()
calls to the new instance, allowing you to extract
any useful dynamic state from the previous instance.
Note that the data you retrieve here should only be used
as an optimization for handling configuration changes. You should always
be able to handle getting a null pointer back, and an activity must
still be able to restore itself to its previous state (through the
normal onSaveInstanceState(Bundle)
mechanism) even if this
function returns null.
Note: For most cases you should use the Fragment
API
Fragment.setRetainInstance(boolean)
instead; this is also
available on older platforms through the Android support libraries.
onRetainNonConfigurationInstance()
public Object onRetainNonConfigurationInstance()
getLastNonConfigurationInstance()
in the new activity
instance.
If you are targeting Build.VERSION_CODES.HONEYCOMB
or later, consider instead using a Fragment
with
Fragment.setRetainInstance(boolean
.
This function is called purely as an optimization, and you must not rely on it being called. When it is called, a number of guarantees will be made to help optimize configuration switching:
onStop()
and
onDestroy()
.
onDestroy()
is called. In particular,
no messages will be dispatched during this time (when the returned
object does not have an activity to be associated with).
getLastNonConfigurationInstance()
method of the following
activity instance as described there.
These guarantees are designed so that an activity can use this API to propagate extensive state from the old to new activity instance, from loaded bitmaps, to network connections, to evenly actively running threads. Note that you should not propagate any data that may change based on the configuration, including any data loaded from resources such as strings, layouts, or drawables.
The guarantee of no message handling during the switch to the next
activity simplifies use with active objects. For example if your retained
state is an AsyncTask
you are guaranteed that its
call back functions (like AsyncTask.onPostExecute(Result)
) will
not be called from the call here until you execute the next instance's
onCreate(Bundle)
. (Note however that there is of course no such
guarantee for AsyncTask.doInBackground(Params...)
since that is
running in a separate thread.)
Note: For most cases you should use the Fragment
API
Fragment.setRetainInstance(boolean)
instead; this is also
available on older platforms through the Android support libraries.
public void onLowMemory()
ComponentCallbacks
You should implement this method to release any caches or other unnecessary resources you may be holding on to. The system will perform a garbage collection for you after returning from this method.
Preferably, you should implement ComponentCallbacks2.onTrimMemory(int)
from
ComponentCallbacks2
to incrementally unload your resources based on various
levels of memory demands. That API is available for API level 14 and higher, so you should
only use this ComponentCallbacks.onLowMemory()
method as a fallback for older versions, which can be
treated the same as ComponentCallbacks2.onTrimMemory(int)
with the ComponentCallbacks2.TRIM_MEMORY_COMPLETE
level.
onLowMemory
in interface ComponentCallbacks
public void onTrimMemory(int level)
ComponentCallbacks2
To retrieve the processes current trim level at any point, you can
use ActivityManager.getMyMemoryState(RunningAppProcessInfo)
.
onTrimMemory
in interface ComponentCallbacks2
level
- The context of the trim, giving a hint of the amount of
trimming the application may like to perform. May be
ComponentCallbacks2.TRIM_MEMORY_COMPLETE
, ComponentCallbacks2.TRIM_MEMORY_MODERATE
,
ComponentCallbacks2.TRIM_MEMORY_BACKGROUND
, ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN
,
ComponentCallbacks2.TRIM_MEMORY_RUNNING_CRITICAL
, ComponentCallbacks2.TRIM_MEMORY_RUNNING_LOW
,
or ComponentCallbacks2.TRIM_MEMORY_RUNNING_MODERATE
.public FragmentManager getFragmentManager()
public void onAttachFragment(Fragment fragment)
Fragment.onAttach()
method and before Fragment.onCreate()
.@Deprecated public final Cursor managedQuery(Uri uri, String[] projection, String selection, String sortOrder)
CursorLoader
instead.ContentResolver.query(android.net.Uri , String[], String, String[], String)
that gives the resulting Cursor
to call
startManagingCursor(android.database.Cursor)
so that the activity will manage its
lifecycle for you.
If you are targeting Build.VERSION_CODES.HONEYCOMB
or later, consider instead using LoaderManager
instead, available
via getLoaderManager()
.
Warning: Do not call Cursor.close()
on a cursor obtained using
this method, because the activity will do that for you at the appropriate time. However, if
you call stopManagingCursor(android.database.Cursor)
on a cursor from a managed query, the system will
not automatically close the cursor and, in that case, you must call
Cursor.close()
.
uri
- The URI of the content provider to query.projection
- List of columns to return.selection
- SQL WHERE clause.sortOrder
- SQL ORDER BY clause.ContentResolver.query(android.net.Uri , String[], String, String[], String)
,
startManagingCursor(android.database.Cursor)
@Deprecated public final Cursor managedQuery(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder)
CursorLoader
instead.ContentResolver.query(android.net.Uri , String[], String, String[], String)
that gives the resulting Cursor
to call
startManagingCursor(android.database.Cursor)
so that the activity will manage its
lifecycle for you.
If you are targeting Build.VERSION_CODES.HONEYCOMB
or later, consider instead using LoaderManager
instead, available
via getLoaderManager()
.
Warning: Do not call Cursor.close()
on a cursor obtained using
this method, because the activity will do that for you at the appropriate time. However, if
you call stopManagingCursor(android.database.Cursor)
on a cursor from a managed query, the system will
not automatically close the cursor and, in that case, you must call
Cursor.close()
.
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 pesentsortOrder
- SQL ORDER BY clause.ContentResolver.query(android.net.Uri , String[], String, String[], String)
,
startManagingCursor(android.database.Cursor)
@Deprecated public void startManagingCursor(Cursor c)
CursorLoader
class with
LoaderManager
instead; this is also
available on older platforms through the Android compatibility package.Cursor
's lifecycle for you based on the activity's lifecycle.
That is, when the activity is stopped it will automatically call
Cursor.deactivate()
on the given Cursor, and when it is later restarted
it will call Cursor.requery()
for you. When the activity is
destroyed, all managed Cursors will be closed automatically.
If you are targeting Build.VERSION_CODES.HONEYCOMB
or later, consider instead using LoaderManager
instead, available
via getLoaderManager()
.
Warning: Do not call Cursor.close()
on cursor obtained from
managedQuery(android.net.Uri, java.lang.String[], java.lang.String, java.lang.String)
, because the activity will do that for you at the appropriate time.
However, if you call stopManagingCursor(android.database.Cursor)
on a cursor from a managed query, the system
will not automatically close the cursor and, in that case, you must call
Cursor.close()
.
c
- The Cursor to be managed.managedQuery(android.net.Uri , String[], String, String[], String)
,
stopManagingCursor(android.database.Cursor)
@Deprecated public void stopManagingCursor(Cursor c)
CursorLoader
class with
LoaderManager
instead; this is also
available on older platforms through the Android compatibility package.startManagingCursor(android.database.Cursor)
, stop the activity's management of that
cursor.
Warning: After calling this method on a cursor from a managed query,
the system will not automatically close the cursor and you must call
Cursor.close()
.
c
- The Cursor that was being managed.startManagingCursor(android.database.Cursor)
@Deprecated public void setPersistent(boolean isPersistent)
Build.VERSION_CODES.GINGERBREAD
this is a no-op.public View findViewById(@IdRes int id)
onCreate(android.os.Bundle)
.public ActionBar getActionBar()
public void setActionBar(Toolbar toolbar)
Toolbar
to act as the ActionBar
for this
Activity window.
When set to a non-null value the getActionBar()
method will return
an ActionBar
object that can be used to control the given toolbar as if it were
a traditional window decor action bar. The toolbar's menu will be populated with the
Activity's options menu and the navigation button will be wired through the standard
home
menu select action.
In order to use a Toolbar within the Activity's window content the application
must not request the window feature FEATURE_ACTION_BAR
.
toolbar
- Toolbar to set as the Activity's action bar, or null
to clear itpublic void setContentView(@LayoutRes int layoutResID)
layoutResID
- Resource ID to be inflated.setContentView(android.view.View)
,
setContentView(android.view.View, android.view.ViewGroup.LayoutParams)
public void setContentView(View view)
ViewGroup.LayoutParams#MATCH_PARENT
. To use
your own layout parameters, invoke
setContentView(android.view.View, android.view.ViewGroup.LayoutParams)
instead.view
- The desired content to display.setContentView(int)
,
setContentView(android.view.View, android.view.ViewGroup.LayoutParams)
public void setContentView(View view, ViewGroup.LayoutParams params)
view
- The desired content to display.params
- Layout parameters for the view.setContentView(android.view.View)
,
setContentView(int)
public void addContentView(View view, ViewGroup.LayoutParams params)
view
- The desired content to display.params
- Layout parameters for the view.public TransitionManager getContentTransitionManager()
TransitionManager
responsible for default transitions in this window.
Requires Window.FEATURE_CONTENT_TRANSITIONS
.
This method will return non-null after content has been initialized (e.g. by using
setContentView(int)
) if Window.FEATURE_CONTENT_TRANSITIONS
has been granted.
public void setContentTransitionManager(TransitionManager tm)
TransitionManager
to use for default transitions in this window.
Requires Window.FEATURE_CONTENT_TRANSITIONS
.tm
- The TransitionManager to use for scene changes.public Scene getContentScene()
Scene
representing this window's current content.
Requires Window.FEATURE_CONTENT_TRANSITIONS
.
This method will return null if the current content is not represented by a Scene.
public void setFinishOnTouchOutside(boolean finish)
public final void setDefaultKeyMode(int mode)
DEFAULT_KEYS_DISABLE
) will simply drop them on the
floor. Other modes allow you to launch the dialer
(DEFAULT_KEYS_DIALER
), execute a shortcut in your options
menu without requiring the menu key be held down
(DEFAULT_KEYS_SHORTCUT
), or launch a search (DEFAULT_KEYS_SEARCH_LOCAL
and DEFAULT_KEYS_SEARCH_GLOBAL
).
Note that the mode selected here does not impact the default handling of system keys, such as the "back" and "menu" keys, and your activity and its views always get a first chance to receive and handle all application keys.
mode
- The desired default key mode constant.DEFAULT_KEYS_DISABLE
,
DEFAULT_KEYS_DIALER
,
DEFAULT_KEYS_SHORTCUT
,
DEFAULT_KEYS_SEARCH_LOCAL
,
DEFAULT_KEYS_SEARCH_GLOBAL
,
onKeyDown(int, android.view.KeyEvent)
public boolean onKeyDown(int keyCode, KeyEvent event)
If the focused view didn't want this event, this method is called.
The default implementation takes care of KeyEvent.KEYCODE_BACK
by calling onBackPressed()
, though the behavior varies based
on the application compatibility mode: for
Build.VERSION_CODES.ECLAIR
or later applications,
it will set up the dispatch to call onKeyUp(int, android.view.KeyEvent)
where the action
will be performed; for earlier applications, it will perform the
action immediately in on-down, as those versions of the platform
behaved.
Other additional default key handling may be performed
if configured with setDefaultKeyMode(int)
.
onKeyDown
in interface KeyEvent.Callback
keyCode
- The value in event.getKeyCode().event
- Description of the key event.true
to prevent this event from being propagated
further, or false
to indicate that you have not handled
this event and it should continue to be propagated.onKeyUp(int, android.view.KeyEvent)
,
KeyEvent
public boolean onKeyLongPress(int keyCode, KeyEvent event)
KeyEvent.Callback.onKeyLongPress()
: always returns false (doesn't handle
the event).onKeyLongPress
in interface KeyEvent.Callback
keyCode
- The value in event.getKeyCode().event
- Description of the key event.public boolean onKeyUp(int keyCode, KeyEvent event)
The default implementation handles KEYCODE_BACK to stop the activity and go back.
onKeyUp
in interface KeyEvent.Callback
keyCode
- The value in event.getKeyCode().event
- Description of the key event.true
to prevent this event from being propagated
further, or false
to indicate that you have not handled
this event and it should continue to be propagated.onKeyDown(int, android.view.KeyEvent)
,
KeyEvent
public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event)
KeyEvent.Callback.onKeyMultiple()
: always returns false (doesn't handle
the event).onKeyMultiple
in interface KeyEvent.Callback
keyCode
- The value in event.getKeyCode().repeatCount
- Number of pairs as returned by event.getRepeatCount().event
- Description of the key event.public void onBackPressed()
public boolean onKeyShortcut(int keyCode, KeyEvent event)
shortcut
property of menu items.keyCode
- The value in event.getKeyCode().event
- Description of the key event.public boolean onTouchEvent(MotionEvent event)
event
- The touch screen event being processed.public boolean onTrackballEvent(MotionEvent event)
event
- The trackball event being processed.public boolean onGenericMotionEvent(MotionEvent event)
Generic motion events describe joystick movements, mouse hovers, track pad
touches, scroll wheel movements and other input events. The
source
of the motion event specifies
the class of input that was received. Implementations of this method
must examine the bits in the source before processing the event.
The following code example shows how this is done.
Generic motion events with source class
InputDevice.SOURCE_CLASS_POINTER
are delivered to the view under the pointer. All other generic motion events are
delivered to the focused view.
See View.onGenericMotionEvent(MotionEvent)
for an example of how to
handle this event.
event
- The generic motion event being processed.public void onUserInteraction()
onUserLeaveHint()
are intended to help
activities manage status bar notifications intelligently; specifically,
for helping activities determine the proper time to cancel a notfication.
All calls to your activity's onUserLeaveHint()
callback will
be accompanied by calls to onUserInteraction()
. This
ensures that your activity will be told of relevant user activity such
as pulling down the notification pane and touching an item there.
Note that this callback will be invoked for the touch down action that begins a touch gesture, but may not be invoked for the touch-moved and touch-up actions that follow.
onUserLeaveHint()
public void onWindowAttributesChanged(WindowManager.LayoutParams params)
Window.Callback
onWindowAttributesChanged
in interface Window.Callback
public void onContentChanged()
Window.Callback
Window.setContentView
or
Window.addContentView
).onContentChanged
in interface Window.Callback
public void onWindowFocusChanged(boolean hasFocus)
Window
of the activity gains or loses
focus. This is the best indicator of whether this activity is visible
to the user. The default implementation clears the key tracking
state, so should always be called.
Note that this provides information about global focus state, which
is managed independently of activity lifecycles. As such, while focus
changes will generally have some relation to lifecycle changes (an
activity that is stopped will not generally get window focus), you
should not rely on any particular order between the callbacks here and
those in the other lifecycle methods such as onResume()
.
As a general rule, however, a resumed activity will have window focus... unless it has displayed other dialogs or popups that take input focus, in which case the activity itself will not have focus when the other windows have it. Likewise, the system may display system-level windows (such as the status bar notification panel or a system alert) which will temporarily take window input focus without pausing the foreground activity.
onWindowFocusChanged
in interface Window.Callback
hasFocus
- Whether the window of this activity has focus.hasWindowFocus()
,
onResume()
,
View.onWindowFocusChanged(boolean)
public void onAttachedToWindow()
View.onAttachedToWindow()
for more information.onAttachedToWindow
in interface Window.Callback
View.onAttachedToWindow()
public void onDetachedFromWindow()
View.onDetachedFromWindow()
for more information.onDetachedFromWindow
in interface Window.Callback
View.onDetachedFromWindow()
public boolean hasWindowFocus()
onWindowAttributesChanged(android.view.WindowManager.LayoutParams)
public void onWindowDismissed(boolean finishTask)
onWindowDismissed
in interface Window.OnWindowDismissedCallback
finishTask
- True if the task should also be finished.public void exitFreeformMode() throws RemoteException
ActivityManager.StackId.FREEFORM_WORKSPACE_STACK_ID
to
ActivityManager.StackId.FULLSCREEN_WORKSPACE_STACK_ID
stack.exitFreeformMode
in interface Window.WindowControllerCallback
RemoteException
public int getWindowStackId() throws RemoteException
getWindowStackId
in interface Window.WindowControllerCallback
RemoteException
public void enterPictureInPictureModeIfPossible()
enterPictureInPictureModeIfPossible
in interface Window.WindowControllerCallback
android.R.attr#supportsPictureInPicture
public boolean dispatchKeyEvent(KeyEvent event)
dispatchKeyEvent
in interface Window.Callback
event
- The key event.public boolean dispatchKeyShortcutEvent(KeyEvent event)
dispatchKeyShortcutEvent
in interface Window.Callback
event
- The key shortcut event.public boolean dispatchTouchEvent(MotionEvent ev)
dispatchTouchEvent
in interface Window.Callback
ev
- The touch screen event.public boolean dispatchTrackballEvent(MotionEvent ev)
dispatchTrackballEvent
in interface Window.Callback
ev
- The trackball event.public boolean dispatchGenericMotionEvent(MotionEvent ev)
dispatchGenericMotionEvent
in interface Window.Callback
ev
- The generic motion event.public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event)
Window.Callback
AccessibilityEvent
s.dispatchPopulateAccessibilityEvent
in interface Window.Callback
event
- The event.public View onCreatePanelView(int featureId)
Window.Callback.onCreatePanelView(int)
for activities. This
simply returns null so that all panel sub-windows will have the default
menu behavior.onCreatePanelView
in interface Window.Callback
featureId
- Which panel is being created.Window.Callback.onPreparePanel(int, android.view.View, android.view.Menu)
public boolean onCreatePanelMenu(int featureId, Menu menu)
Window.Callback.onCreatePanelMenu(int, android.view.Menu)
for activities. This calls through to the new
onCreateOptionsMenu(android.view.Menu)
method for the
Window.FEATURE_OPTIONS_PANEL
panel,
so that subclasses of Activity don't need to deal with feature codes.onCreatePanelMenu
in interface Window.Callback
featureId
- The panel being created.menu
- The menu inside the panel.public boolean onPreparePanel(int featureId, View view, Menu menu)
Window.Callback.onPreparePanel(int, android.view.View, android.view.Menu)
for activities. This
calls through to the new onPrepareOptionsMenu(android.view.Menu)
method for the
Window.FEATURE_OPTIONS_PANEL
panel, so that subclasses of
Activity don't need to deal with feature codes.onPreparePanel
in interface Window.Callback
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.Window.Callback.onCreatePanelView(int)
public boolean onMenuOpened(int featureId, Menu menu)
onMenuOpened
in interface Window.Callback
featureId
- The panel that the menu is in.menu
- The menu that is opened.public boolean onMenuItemSelected(int featureId, MenuItem item)
Window.Callback.onMenuItemSelected(int, android.view.MenuItem)
for activities. This calls through to the new
onOptionsItemSelected(android.view.MenuItem)
method for the
Window.FEATURE_OPTIONS_PANEL
panel, so that subclasses of
Activity don't need to deal with feature codes.onMenuItemSelected
in interface Window.Callback
featureId
- The panel that the menu is in.item
- The menu item that was selected.public void onPanelClosed(int featureId, Menu menu)
Window.Callback.onPanelClosed(int, Menu)
for
activities. This calls through to onOptionsMenuClosed(Menu)
method for the Window.FEATURE_OPTIONS_PANEL
panel,
so that subclasses of Activity don't need to deal with feature codes.
For context menus (Window.FEATURE_CONTEXT_MENU
), the
onContextMenuClosed(Menu)
will be called.onPanelClosed
in interface Window.Callback
featureId
- The panel that is being displayed.menu
- If onCreatePanelView() returned null, this is the Menu
being displayed in the panel.public void invalidateOptionsMenu()
onCreateOptionsMenu(Menu)
method will be called the next
time it needs to be displayed.public boolean onCreateOptionsMenu(Menu menu)
This is only called once, the first time the options menu is
displayed. To update the menu every time it is displayed, see
onPrepareOptionsMenu(android.view.Menu)
.
The default implementation populates the menu with standard system
menu items. These are placed in the Menu.CATEGORY_SYSTEM
group so that
they will be correctly ordered with application-defined menu items.
Deriving classes should always call through to the base implementation.
You can safely hold on to menu (and any items created from it), making modifications to it as desired, until the next time onCreateOptionsMenu() is called.
When you add items to the menu, you can implement the Activity's
onOptionsItemSelected(android.view.MenuItem)
method to handle them there.
menu
- The options menu in which you place your items.onPrepareOptionsMenu(android.view.Menu)
,
onOptionsItemSelected(android.view.MenuItem)
public boolean onPrepareOptionsMenu(Menu menu)
The default implementation updates the system menu items based on the activity's state. Deriving classes should always call through to the base class implementation.
menu
- The options menu as last shown or first initialized by
onCreateOptionsMenu().onCreateOptionsMenu(android.view.Menu)
public boolean onOptionsItemSelected(MenuItem item)
Derived classes should call through to the base class for it to perform the default menu handling.
item
- The menu item that was selected.onCreateOptionsMenu(android.view.Menu)
public boolean onNavigateUp()
If the attribute parentActivityName
was specified in the manifest for this activity or an activity-alias to it,
default Up navigation will be handled automatically. If any activity
along the parent chain requires extra Intent arguments, the Activity subclass
should override the method onPrepareNavigateUpTaskStack(TaskStackBuilder)
to supply those arguments.
See Tasks and Back Stack from the developer guide and Navigation from the design guide for more information about navigating within your app.
See the TaskStackBuilder
class and the Activity methods
getParentActivityIntent()
, shouldUpRecreateTask(Intent)
, and
navigateUpTo(Intent)
for help implementing custom Up navigation.
The AppNavigation sample application in the Android SDK is also available for reference.
public boolean onNavigateUpFromChild(Activity child)
child
- The activity making the call.public void onCreateNavigateUpTaskStack(TaskStackBuilder builder)
The default implementation of this method adds the parent chain of this activity
as specified in the manifest to the supplied TaskStackBuilder
. Applications
may choose to override this method to construct the desired task stack in a different
way.
This method will be invoked by the default implementation of onNavigateUp()
if shouldUpRecreateTask(Intent)
returns true when supplied with the intent
returned by getParentActivityIntent()
.
Applications that wish to supply extra Intent parameters to the parent stack defined
by the manifest should override onPrepareNavigateUpTaskStack(TaskStackBuilder)
.
builder
- An empty TaskStackBuilder - the application should add intents representing
the desired task stackpublic void onPrepareNavigateUpTaskStack(TaskStackBuilder builder)
This method receives the TaskStackBuilder
with the constructed series of
Intents as generated by onCreateNavigateUpTaskStack(TaskStackBuilder)
.
If any extra data should be added to these intents before launching the new task,
the application should override this method and add that data here.
builder
- A TaskStackBuilder that has been populated with Intents by
onCreateNavigateUpTaskStack.public void onOptionsMenuClosed(Menu menu)
menu
- The options menu as last shown or first initialized by
onCreateOptionsMenu().public void openOptionsMenu()
public void closeOptionsMenu()
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo)
view
is about to be shown.
Unlike onCreateOptionsMenu(Menu)
, this will be called every
time the context menu is about to be shown and should be populated for
the view (or item inside the view for AdapterView
subclasses,
this can be found in the menuInfo
)).
Use onContextItemSelected(android.view.MenuItem)
to know when an
item has been selected.
It is not safe to hold onto the context menu after this method returns.
onCreateContextMenu
in interface View.OnCreateContextMenuListener
menu
- The context menu that is being builtv
- The view for which the context menu is being builtmenuInfo
- Extra information about the item for which the
context menu should be shown. This information will vary
depending on the class of v.public void registerForContextMenu(View view)
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.view
- The view that should show a context menu.unregisterForContextMenu(View)
public void unregisterForContextMenu(View view)
View.OnCreateContextMenuListener
on the view.view
- The view that should stop showing a context menu.registerForContextMenu(View)
public void openContextMenu(View view)
view
.
The view
should have been added via
registerForContextMenu(View)
.view
- The view to show the context menu for.public void closeContextMenu()
public boolean onContextItemSelected(MenuItem item)
Use MenuItem.getMenuInfo()
to get extra information set by the
View that added this menu item.
Derived classes should call through to the base class for it to perform the default menu handling.
item
- The context menu item that was selected.public void onContextMenuClosed(Menu menu)
menu
- The context menu that is being closed.@Deprecated protected Dialog onCreateDialog(int id)
onCreateDialog(int, Bundle)
.@Deprecated protected Dialog onCreateDialog(int id, Bundle args)
DialogFragment
class with
FragmentManager
instead; this is also
available on older platforms through the Android compatibility package.onCreateDialog(int)
for compatibility.
If you are targeting Build.VERSION_CODES.HONEYCOMB
or later, consider instead using a DialogFragment
instead.
If you use showDialog(int)
, the activity will call through to
this method the first time, and hang onto it thereafter. Any dialog
that is created by this method will automatically be saved and restored
for you, including whether it is showing.
If you would like the activity to manage saving and restoring dialogs
for you, you should override this method and handle any ids that are
passed to showDialog(int)
.
If you would like an opportunity to prepare your dialog before it is shown,
override onPrepareDialog(int, Dialog, Bundle)
.
id
- The id of the dialog.args
- The dialog arguments provided to showDialog(int, Bundle)
.onPrepareDialog(int, Dialog, Bundle)
,
showDialog(int, Bundle)
,
dismissDialog(int)
,
removeDialog(int)
@Deprecated protected void onPrepareDialog(int id, Dialog dialog)
onPrepareDialog(int, Dialog, Bundle)
.@Deprecated protected void onPrepareDialog(int id, Dialog dialog, Bundle args)
DialogFragment
class with
FragmentManager
instead; this is also
available on older platforms through the Android compatibility package.onPrepareDialog(int, Dialog)
for compatibility.
Override this if you need to update a managed dialog based on the state of the application each time it is shown. For example, a time picker dialog might want to be updated with the current time. You should call through to the superclass's implementation. The default implementation will set this Activity as the owner activity on the Dialog.
id
- The id of the managed dialog.dialog
- The dialog.args
- The dialog arguments provided to showDialog(int, Bundle)
.onCreateDialog(int, Bundle)
,
showDialog(int)
,
dismissDialog(int)
,
removeDialog(int)
@Deprecated public final void showDialog(int id)
DialogFragment
class with
FragmentManager
instead; this is also
available on older platforms through the Android compatibility package.showDialog(int, Bundle)
that does not
take any arguments. Simply calls showDialog(int, Bundle)
with null arguments.@Deprecated public final boolean showDialog(int id, Bundle args)
DialogFragment
class with
FragmentManager
instead; this is also
available on older platforms through the Android compatibility package.onCreateDialog(int, Bundle)
will be made with the same id the first time this is called for a given
id. From thereafter, the dialog will be automatically saved and restored.
If you are targeting Build.VERSION_CODES.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.
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.onCreateDialog(int, Bundle)
returns false.Dialog
,
onCreateDialog(int, Bundle)
,
onPrepareDialog(int, Dialog, Bundle)
,
dismissDialog(int)
,
removeDialog(int)
@Deprecated public final void dismissDialog(int id)
DialogFragment
class with
FragmentManager
instead; this is also
available on older platforms through the Android compatibility package.showDialog(int)
.id
- The id of the managed dialog.IllegalArgumentException
- if the id was not previously shown via
showDialog(int)
.onCreateDialog(int, Bundle)
,
onPrepareDialog(int, Dialog, Bundle)
,
showDialog(int)
,
removeDialog(int)
@Deprecated public final void removeDialog(int id)
DialogFragment
class with
FragmentManager
instead; this is also
available on older platforms through the Android compatibility package.This can be useful if you know that you will never show a dialog again and want to avoid the overhead of saving and restoring it in the future.
As of Build.VERSION_CODES.GINGERBREAD
, this function
will not throw an exception if you try to remove an ID that does not
currently have an associated dialog.
id
- The id of the managed dialog.onCreateDialog(int, Bundle)
,
onPrepareDialog(int, Dialog, Bundle)
,
showDialog(int)
,
dismissDialog(int)
public boolean onSearchRequested(SearchEvent searchEvent)
You can use this function as a simple way to launch the search UI, in response to a
menu item, search button, or other widgets within your activity. Unless overidden,
calling this function is the same as calling
startSearch(null, false, null, false)
, which launches
search for the current activity as specified in its manifest, see SearchManager
.
You can override this function to force global search, e.g. in response to a dedicated search key, or to block search entirely (by simply returning false).
Note: when running in a Configuration.UI_MODE_TYPE_TELEVISION
, the default
implementation changes to simply return false and you must supply your own custom
implementation if you want to support search.
onSearchRequested
in interface Window.Callback
searchEvent
- The SearchEvent
that signaled this search.true
if search launched, and false
if the activity does
not respond to search. The default implementation always returns true
, except
when in Configuration.UI_MODE_TYPE_TELEVISION
mode where it returns false.SearchManager
public boolean onSearchRequested()
Window.Callback
onSearchRequested
in interface Window.Callback
onSearchRequested(SearchEvent)
public final SearchEvent getSearchEvent()
SearchEvent
that triggered the callback, if it exists.onSearchRequested(android.view.SearchEvent)
callback.public void startSearch(String initialQuery, boolean selectInitialQuery, Bundle appSearchData, boolean globalSearch)
It is typically called from onSearchRequested(), either directly from Activity.onSearchRequested() or from an overridden version in any given Activity. If your goal is simply to activate search, it is preferred to call onSearchRequested(), which may have been overridden elsewhere in your Activity. If your goal is to inject specific data such as context data, it is preferred to override onSearchRequested(), so that any callers to it will benefit from the override.
initialQuery
- Any non-null non-empty string will be inserted as
pre-entered text in the search query box.selectInitialQuery
- If true, the initial 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.SearchManager
,
onSearchRequested(android.view.SearchEvent)
public void triggerSearch(String query, Bundle appSearchData)
startSearch(java.lang.String, boolean, android.os.Bundle, boolean)
, but actually fires off the search query after invoking
the search dialog. Made available for testing purposes.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 takeKeyEvents(boolean get)
Window.takeKeyEvents(boolean)
public final boolean requestWindowFeature(int featureId)
getWindow().requestFeature()
.featureId
- The desired feature as defined in
Window
.Window.requestFeature(int)
public final void setFeatureDrawableResource(int featureId, @DrawableRes int resId)
Window.setFeatureDrawableResource(int, int)
.public final void setFeatureDrawableUri(int featureId, Uri uri)
Window.setFeatureDrawableUri(int, android.net.Uri)
.public final void setFeatureDrawable(int featureId, Drawable drawable)
Window.setFeatureDrawable(int, Drawable)
.public final void setFeatureDrawableAlpha(int featureId, int alpha)
Window.setFeatureDrawableAlpha(int, int)
.public LayoutInflater getLayoutInflater()
Window.getLayoutInflater()
.public MenuInflater getMenuInflater()
MenuInflater
with this context.public void setTheme(int resid)
Context
setContentView(int)
or
LayoutInflater.inflate(int, android.view.ViewGroup)
).setTheme
in class ContextThemeWrapper
resid
- The style resource describing the theme.protected void onApplyThemeResource(Resources.Theme theme, @StyleRes int resid, boolean first)
ContextThemeWrapper
ContextThemeWrapper.setTheme(int)
and ContextThemeWrapper.getTheme()
to apply a theme
resource to the current Theme object. May be overridden to change the
default (simple) behavior. This method will not be called in multiple
threads simultaneously.onApplyThemeResource
in class ContextThemeWrapper
theme
- the theme being modifiedresid
- the style resource being applied to themefirst
- true
if this is the first time a style is being
applied to themepublic final void requestPermissions(String[] permissions, int requestCode)
#PROTECTION_DANGEROUS dangerous
, regardless whether they are declared by
the platform or a third-party app.
Normal permissions PermissionInfo.PROTECTION_NORMAL
are granted at install time if requested in the manifest. Signature permissions
PermissionInfo.PROTECTION_SIGNATURE
are granted at
install time if requested in the manifest and the signature of your app matches
the signature of the app declaring the permissions.
If your app does not have the requested permissions the user will be presented
with UI for accepting them. After the user has accepted or rejected the
requested permissions you will receive a callback on onRequestPermissionsResult(int, String[], int[])
reporting whether the
permissions were granted or not.
Note that requesting a permission does not guarantee it will be granted and your app should be able to run without having this permission.
This method may start an activity allowing the user to choose which permissions
to grant and which to reject. Hence, you should be prepared that your activity
may be paused and resumed. Further, granting some permissions may require
a restart of you application. In such a case, the system will recreate the
activity stack before delivering the result to onRequestPermissionsResult(int, String[], int[])
.
When checking whether you have a permission you should use ContextWrapper.checkSelfPermission(String)
.
Calling this API for permissions already granted to your app would show UI to the user to decide whether the app can still hold these permissions. This can be useful if the way your app uses data guarded by the permissions changes significantly.
You cannot request a permission if your activity sets noHistory
to
true
because in this case the activity would not receive
result callbacks including onRequestPermissionsResult(int, String[], int[])
.
The RuntimePermissions sample app demonstrates how to use this method to request permissions at run time.
permissions
- The requested permissions. Must me non-null and not empty.requestCode
- Application specific request code to match with a result
reported to onRequestPermissionsResult(int, String[], int[])
.
Should be >= 0.onRequestPermissionsResult(int, String[], int[])
,
ContextWrapper.checkSelfPermission(String)
,
shouldShowRequestPermissionRationale(String)
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults)
requestPermissions(String[], int)
.
Note: It is possible that the permissions request interaction with the user is interrupted. In this case you will receive empty permissions and results arrays which should be treated as a cancellation.
requestCode
- The request code passed in requestPermissions(String[], int)
.permissions
- The requested permissions. Never null.grantResults
- The grant results for the corresponding permissions
which is either PackageManager.PERMISSION_GRANTED
or PackageManager.PERMISSION_DENIED
. Never null.requestPermissions(String[], int)
public boolean shouldShowRequestPermissionRationale(String permission)
For example, if you write a camera app, requesting the camera permission would be expected by the user and no rationale for why it is requested is needed. If however, the app needs location for tagging photos then a non-tech savvy user may wonder how location is related to taking photos. In this case you may choose to show UI with rationale of requesting this permission.
permission
- A permission your app wants to request.ContextWrapper.checkSelfPermission(String)
,
requestPermissions(String[], int)
,
onRequestPermissionsResult(int, String[], int[])
public void startActivityForResult(Intent intent, int requestCode)
startActivityForResult(Intent, int, Bundle)
with no options.intent
- The intent to start.requestCode
- If >= 0, this code will be returned in
onActivityResult() when the activity exits.ActivityNotFoundException
startActivity(android.content.Intent)
public void startActivityForResult(Intent intent, int requestCode, Bundle options)
startActivity(android.content.Intent)
(the activity is not launched as a sub-activity).
Note that this method should only be used with Intent protocols
that are defined to return a result. In other protocols (such as
Intent.ACTION_MAIN
or Intent.ACTION_VIEW
), you may
not get the result when you expect. For example, if the activity you
are launching uses the singleTask launch mode, it will not run in your
task and thus you will immediately receive a cancel result.
As a special case, if you call startActivityForResult() with a requestCode >= 0 during the initial onCreate(Bundle savedInstanceState)/onResume() of your activity, then your window will not be displayed until a result is returned back from the started activity. This is to avoid visible flickering when redirecting to another activity.
This method throws ActivityNotFoundException
if there was no Activity found to run the given Intent.
intent
- The intent to start.requestCode
- If >= 0, this code will be returned in
onActivityResult() when the activity exits.options
- Additional options for how the Activity should be started.
See Context.startActivity(Intent, Bundle)
for more details.ActivityNotFoundException
startActivity(android.content.Intent)
public void startActivityForResultAsUser(Intent intent, int requestCode, UserHandle user)
public void startActivityForResultAsUser(Intent intent, int requestCode, Bundle options, UserHandle user)
public void startActivityAsUser(Intent intent, UserHandle user)
Context
Context.startActivity(Intent)
that allows you to specify the
user the activity will be started for. This is not available to applications
that are not pre-installed on the system image. Using it requires holding
the INTERACT_ACROSS_USERS_FULL permission.startActivityAsUser
in class ContextWrapper
intent
- The description of the activity to start.user
- The UserHandle of the user to start this activity for.public void startActivityAsUser(Intent intent, Bundle options, UserHandle user)
Context
Context.startActivity(Intent, Bundle)
that allows you to specify the
user the activity will be started for. This is not available to applications
that are not pre-installed on the system image. Using it requires holding
the INTERACT_ACROSS_USERS_FULL permission.startActivityAsUser
in class ContextWrapper
intent
- The description of the activity to start.options
- Additional options for how the Activity should be started.
May be null if there are no options. See ActivityOptions
for how to build the Bundle supplied here; there are no supported definitions
for building it manually.user
- The UserHandle of the user to start this activity for.public void startActivityAsCaller(Intent intent, Bundle options, boolean ignoreTargetSecurity, int userId)
intent
- The Intent to start.options
- ActivityOptions or null.ignoreTargetSecurity
- If true, the activity manager will not check whether the
caller it is doing the start is, is actually allowed to start the target activity.
If you set this to true, you must set an explicit component in the Intent and do any
appropriate security checks yourself.userId
- The user the new activity should run as.public void startIntentSenderForResult(IntentSender intent, int requestCode, Intent fillInIntent, int flagsMask, int flagsValues, int extraFlags) throws IntentSender.SendIntentException
startIntentSenderForResult(IntentSender, int,
Intent, int, int, int, Bundle)
with no options.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 IntentSender.sendIntent(android.content.Context, int, android.content.Intent, android.content.IntentSender.OnFinished, android.os.Handler)
.flagsMask
- Intent flags in the original IntentSender that you
would like to change.flagsValues
- Desired values for any bits set in
flagsMaskextraFlags
- Always set to 0.IntentSender.SendIntentException
public void startIntentSenderForResult(IntentSender intent, int requestCode, Intent fillInIntent, int flagsMask, int flagsValues, int extraFlags, Bundle options) throws IntentSender.SendIntentException
startActivityForResult(Intent, int)
, but allowing you
to use a IntentSender to describe the activity to be started. If
the IntentSender is for an activity, that activity will be started
as if you had called the regular startActivityForResult(Intent, int)
here; otherwise, its associated action will be executed (such as
sending a broadcast) as if you had called
IntentSender.sendIntent
on it.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 IntentSender.sendIntent(android.content.Context, int, android.content.Intent, android.content.IntentSender.OnFinished, android.os.Handler)
.flagsMask
- Intent flags in the original IntentSender that you
would like to change.flagsValues
- Desired values for any bits set in
flagsMaskextraFlags
- Always set to 0.options
- Additional options for how the Activity should be started.
See Context.startActivity(Intent, Bundle)
for more details. If options
have also been supplied by the IntentSender, options given here will
override any that conflict with those given by the IntentSender.IntentSender.SendIntentException
public void startActivity(Intent intent)
startActivity(Intent, Bundle)
with no options
specified.startActivity
in class ContextWrapper
intent
- The intent to start.ActivityNotFoundException
startActivity(Intent, Bundle)
,
startActivityForResult(android.content.Intent, int)
public void startActivity(Intent intent, Bundle options)
Intent.FLAG_ACTIVITY_NEW_TASK
launch flag is not
required; if not specified, the new activity will be added to the
task of the caller.
This method throws ActivityNotFoundException
if there was no Activity found to run the given Intent.
startActivity
in class ContextWrapper
intent
- The intent to start.options
- Additional options for how the Activity should be started.
See Context.startActivity(Intent, Bundle)
for more details.ActivityNotFoundException
startActivity(Intent)
,
startActivityForResult(android.content.Intent, int)
public void startActivities(Intent[] intents)
startActivities(Intent[], Bundle)
with no options
specified.startActivities
in class ContextWrapper
intents
- The intents to start.ActivityNotFoundException
startActivities(Intent[], Bundle)
,
startActivityForResult(android.content.Intent, int)
public void startActivities(Intent[] intents, Bundle options)
Intent.FLAG_ACTIVITY_NEW_TASK
launch flag is not
required; if not specified, the new activity will be added to the
task of the caller.
This method throws ActivityNotFoundException
if there was no Activity found to run the given Intent.
startActivities
in class ContextWrapper
intents
- The intents to start.options
- Additional options for how the Activity should be started.
See Context.startActivity(Intent, Bundle)
for more details.ActivityNotFoundException
startActivities(Intent[])
,
startActivityForResult(android.content.Intent, int)
public void startIntentSender(IntentSender intent, Intent fillInIntent, int flagsMask, int flagsValues, int extraFlags) throws IntentSender.SendIntentException
startIntentSender(IntentSender, Intent, int, int, int, Bundle)
with no options.startIntentSender
in class ContextWrapper
intent
- The IntentSender to launch.fillInIntent
- If non-null, this will be provided as the
intent parameter to IntentSender.sendIntent(android.content.Context, int, android.content.Intent, android.content.IntentSender.OnFinished, android.os.Handler)
.flagsMask
- Intent flags in the original IntentSender that you
would like to change.flagsValues
- Desired values for any bits set in
flagsMaskextraFlags
- Always set to 0.IntentSender.SendIntentException
Context.startActivity(Intent)
,
Context.startIntentSender(IntentSender, Intent, int, int, int, Bundle)
public void startIntentSender(IntentSender intent, Intent fillInIntent, int flagsMask, int flagsValues, int extraFlags, Bundle options) throws IntentSender.SendIntentException
startActivity(Intent, Bundle)
, but taking a IntentSender
to start; see
startIntentSenderForResult(IntentSender, int, Intent, int, int, int, Bundle)
for more information.startIntentSender
in class ContextWrapper
intent
- The IntentSender to launch.fillInIntent
- If non-null, this will be provided as the
intent parameter to IntentSender.sendIntent(android.content.Context, int, android.content.Intent, android.content.IntentSender.OnFinished, android.os.Handler)
.flagsMask
- Intent flags in the original IntentSender that you
would like to change.flagsValues
- Desired values for any bits set in
flagsMaskextraFlags
- Always set to 0.options
- Additional options for how the Activity should be started.
See Context.startActivity(Intent, Bundle)
for more details. If options
have also been supplied by the IntentSender, options given here will
override any that conflict with those given by the IntentSender.IntentSender.SendIntentException
Context.startActivity(Intent, Bundle)
,
Context.startIntentSender(IntentSender, Intent, int, int, int)
public boolean startActivityIfNeeded(Intent intent, int requestCode)
startActivityIfNeeded(Intent, int, Bundle)
with no options.intent
- The intent to start.requestCode
- If >= 0, this code will be returned in
onActivityResult() when the activity exits, as described in
startActivityForResult(android.content.Intent, int)
.startActivity(android.content.Intent)
,
startActivityForResult(android.content.Intent, int)
public boolean startActivityIfNeeded(Intent intent, int requestCode, Bundle options)
startActivityForResult(Intent, int)
except: if you are
using the Intent.FLAG_ACTIVITY_SINGLE_TOP
flag, or
singleTask or singleTop
launchMode
,
and the activity
that handles intent is the same as your currently running
activity, then a new instance is not needed. In this case, instead of
the normal behavior of calling onNewIntent(android.content.Intent)
this function will
return and you can handle the Intent yourself.
This function can only be called from a top-level activity; if it is called from a child activity, a runtime exception will be thrown.
intent
- The intent to start.requestCode
- If >= 0, this code will be returned in
onActivityResult() when the activity exits, as described in
startActivityForResult(android.content.Intent, int)
.options
- Additional options for how the Activity should be started.
See Context.startActivity(Intent, Bundle)
for more details.startActivity(android.content.Intent)
,
startActivityForResult(android.content.Intent, int)
public boolean startNextMatchingActivity(Intent intent)
startNextMatchingActivity(Intent, Bundle)
with
no options.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.public boolean startNextMatchingActivity(Intent intent, Bundle options)
onCreate(android.os.Bundle)
with the Intent returned by getIntent()
.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.options
- Additional options for how the Activity should be started.
See Context.startActivity(Intent, Bundle)
for more details.public void startActivityFromChild(Activity child, Intent intent, int requestCode)
startActivityFromChild(Activity, Intent, int, Bundle)
with no options.child
- The activity making the call.intent
- The intent to start.requestCode
- Reply request code. < 0 if reply is not requested.ActivityNotFoundException
startActivity(android.content.Intent)
,
startActivityForResult(android.content.Intent, int)
public void startActivityFromChild(Activity child, Intent intent, int requestCode, Bundle options)
startActivity(android.content.Intent)
or startActivityForResult(android.content.Intent, int)
method.
This method throws ActivityNotFoundException
if there was no Activity found to run the given Intent.
child
- The activity making the call.intent
- The intent to start.requestCode
- Reply request code. < 0 if reply is not requested.options
- Additional options for how the Activity should be started.
See Context.startActivity(Intent, Bundle)
for more details.ActivityNotFoundException
startActivity(android.content.Intent)
,
startActivityForResult(android.content.Intent, int)
public void startActivityFromFragment(Fragment fragment, Intent intent, int requestCode)
startActivityFromFragment(Fragment, Intent, int, Bundle)
with no options.fragment
- The fragment making the call.intent
- The intent to start.requestCode
- Reply request code. < 0 if reply is not requested.ActivityNotFoundException
Fragment.startActivity(android.content.Intent)
,
Fragment.startActivityForResult(android.content.Intent, int)
public void startActivityFromFragment(Fragment fragment, Intent intent, int requestCode, Bundle options)
Fragment.startActivity(android.content.Intent)
or Fragment.startActivityForResult(android.content.Intent, int)
method.
This method throws ActivityNotFoundException
if there was no Activity found to run the given Intent.
fragment
- The fragment making the call.intent
- The intent to start.requestCode
- Reply request code. < 0 if reply is not requested.options
- Additional options for how the Activity should be started.
See Context.startActivity(Intent, Bundle)
for more details.ActivityNotFoundException
Fragment.startActivity(android.content.Intent)
,
Fragment.startActivityForResult(android.content.Intent, int)
public void startActivityForResult(String who, Intent intent, int requestCode, Bundle options)
Context
Context.startActivity(Intent, Bundle)
that returns a result to the caller. This
is only supported for Views and Fragments.startActivityForResult
in class ContextWrapper
who
- The identifier for the calling element that will receive the result.intent
- The intent to start.requestCode
- The code that will be returned with onActivityResult() identifying this
request.options
- Additional options for how the Activity should be started.
May be null if there are no options. See ActivityOptions
for how to build the Bundle supplied here; there are no supported definitions
for building it manually.public boolean canStartActivityForResult()
Context
Context.startActivityForResult(String, Intent, int, Bundle)
.canStartActivityForResult
in class ContextWrapper
public void startIntentSenderFromChild(Activity child, IntentSender intent, int requestCode, Intent fillInIntent, int flagsMask, int flagsValues, int extraFlags) throws IntentSender.SendIntentException
startIntentSenderFromChild(Activity, IntentSender,
int, Intent, int, int, int, Bundle)
with no options.IntentSender.SendIntentException
public void startIntentSenderFromChild(Activity child, IntentSender intent, int requestCode, Intent fillInIntent, int flagsMask, int flagsValues, int extraFlags, Bundle options) throws IntentSender.SendIntentException
startActivityFromChild(Activity, Intent, int)
, but
taking a IntentSender; see
startIntentSenderForResult(IntentSender, int, Intent, int, int, int)
for more information.IntentSender.SendIntentException
public void startIntentSenderFromChildFragment(Fragment child, IntentSender intent, int requestCode, Intent fillInIntent, int flagsMask, int flagsValues, int extraFlags, Bundle options) throws IntentSender.SendIntentException
startIntentSenderFromChild(android.app.Activity, android.content.IntentSender, int, android.content.Intent, int, int, int)
, but taking a Fragment; see
startIntentSenderForResult(IntentSender, int, Intent, int, int, int)
for more information.IntentSender.SendIntentException
public void overridePendingTransition(int enterAnim, int exitAnim)
startActivity(Intent)
or finish(int)
to specify an explicit transition animation to
perform next.
As of Build.VERSION_CODES.JELLY_BEAN
an alternative
to using this with starting activities is to supply the desired animation
information through a ActivityOptions
bundle to
startActivity(Intent, Bundle)
or a related function. This allows
you to specify a custom animation even when starting an activity from
outside the context of the current top activity.
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 final void setResult(int resultCode)
resultCode
- The result code to propagate back to the originating
activity, often RESULT_CANCELED or RESULT_OKRESULT_CANCELED
,
RESULT_OK
,
RESULT_FIRST_USER
,
setResult(int, Intent)
public final void setResult(int resultCode, Intent data)
As of Build.VERSION_CODES.GINGERBREAD
, the Intent
you supply here can have Intent.FLAG_GRANT_READ_URI_PERMISSION
and/or Intent.FLAG_GRANT_WRITE_URI_PERMISSION
set. This will grant the
Activity receiving the result access to the specific URIs in the Intent.
Access will remain until the Activity has finished (it will remain across the hosting
process being killed and other temporary destruction) and will be added
to any existing set of URI permissions it already holds.
resultCode
- The result code to propagate back to the originating
activity, often RESULT_CANCELED or RESULT_OKdata
- The data to propagate back to the originating activity.RESULT_CANCELED
,
RESULT_OK
,
RESULT_FIRST_USER
,
setResult(int)
public Uri getReferrer()
Intent.EXTRA_REFERRER
,
that will be returned as-is; otherwise, if known, an
android-app:
referrer URI containing the
package name that started the Intent will be returned. This may return null if no
referrer can be identified -- it is neither explicitly specified, nor is it known which
application package was involved.
If called while inside the handling of onNewIntent(android.content.Intent)
, this function will
return the referrer that submitted that new intent to the activity. Otherwise, it
always returns the referrer of the original Intent.
Note that this is not a security feature -- you can not trust the referrer information, applications can spoof it.
public Uri onProvideReferrer()
Intent.EXTRA_REFERRER
of any activities started from it.public String getCallingPackage()
setResult()
will be sent to. You can
use this information to validate that the recipient is allowed to
receive the data.
Note: if the calling activity is not expecting a result (that is it
did not use the startActivityForResult(android.content.Intent, int)
form that includes a request code), then the calling package will be
null.
Note: prior to Build.VERSION_CODES.JELLY_BEAN_MR2
,
the result from this method was unstable. If the process hosting the calling
package was no longer running, it would return null instead of the proper package
name. You can use getCallingActivity()
and retrieve the package name
from that instead.
public ComponentName getCallingActivity()
setResult()
will be sent to. You
can use this information to validate that the recipient is allowed to
receive the data.
Note: if the calling activity is not expecting a result (that is it
did not use the startActivityForResult(android.content.Intent, int)
form that includes a request code), then the calling package will be
null.
public void setVisible(boolean visible)
The default value for this is taken from the
android.R.attr#windowNoDisplay
attribute of the activity's theme.
public boolean isFinishing()
finish(int)
on it or someone else
has requested that it finished. This is often used in
onPause()
to determine whether the activity is simply pausing or
completely finishing.finish(int)
public boolean isDestroyed()
onDestroy()
call has been made
on the Activity, so this instance is now dead.public boolean isChangingConfigurations()
onStop()
to determine whether the state needs to be cleaned up or will be passed
on to the next instance of the activity via onRetainNonConfigurationInstance()
.public void recreate()
onDestroy()
and a new instance then created after it.public void finish()
public void finishAffinity()
Note that this finish does not allow you to deliver results to the previous activity, and an exception will be thrown if you are trying to do so.
public void finishFromChild(Activity child)
finish(int)
method. The default implementation simply calls
finish() on this activity (the parent), finishing the entire group.child
- The activity making the call.finish(int)
public void finishAfterTransition()
finish()
is called. If no entry Transition was used, finish() is called
immediately and the Activity exit Transition is run.public void finishActivity(int requestCode)
startActivityForResult(android.content.Intent, int)
.requestCode
- The request code of the activity that you had
given to startActivityForResult(). If there are multiple
activities started with this request code, they
will all be finished.public void finishActivityFromChild(Activity child, int requestCode)
child
- The activity making the call.requestCode
- Request code that had been used to start the
activity.public void finishAndRemoveTask()
public boolean releaseInstance()
protected void onActivityResult(int requestCode, int resultCode, Intent data)
RESULT_CANCELED
if the activity explicitly returned that,
didn't return any result, or crashed during its operation.
You will receive this call immediately before onResume() when your activity is re-starting.
This method is never invoked if your activity sets
noHistory
to
true
.
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").startActivityForResult(android.content.Intent, int)
,
createPendingResult(int, android.content.Intent, int)
,
setResult(int)
public void onActivityReenter(int resultCode, Intent data)
RESULT_CANCELED
and it supports activity
transitions with Window.FEATURE_ACTIVITY_TRANSITIONS
.
The purpose of this function is to let the called Activity send a hint about its state so that this underlying Activity can prepare to be exposed. A call to this method does not guarantee that the called Activity has or will be exiting soon. It only indicates that it will expose this Activity's Window and it has some data to pass to prepare it.
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").public PendingIntent createPendingResult(int requestCode, Intent data, int flags)
onActivityResult(int, int, android.content.Intent)
callback. The created object will be either
one-shot (becoming invalid after a result is sent back) or multiple
(allowing any number of results to be sent through it).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.PendingIntent.FLAG_NO_CREATE
has been
supplied.PendingIntent
public void setRequestedOrientation(int requestedOrientation)
requestedOrientation
- An orientation constant as used in
ActivityInfo.screenOrientation
.public int getRequestedOrientation()
setRequestedOrientation(int)
.ActivityInfo.screenOrientation
.public int getTaskId()
public boolean isTaskRoot()
public boolean moveTaskToBack(boolean nonRoot)
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.public String getLocalClassName()
public ComponentName getComponentName()
public SharedPreferences getPreferences(int mode)
SharedPreferences
object for accessing preferences
that are private to this activity. This simply calls the underlying
ContextWrapper.getSharedPreferences(String, int)
method by passing in this activity's
class name as the preferences name.mode
- Operating mode. Use Context.MODE_PRIVATE
for the default
operation.public Object getSystemService(String name)
Context
Context.WINDOW_SERVICE
("window")
WindowManager
.
Context.LAYOUT_INFLATER_SERVICE
("layout_inflater")
LayoutInflater
for inflating layout resources
in this context.
Context.ACTIVITY_SERVICE
("activity")
ActivityManager
for interacting with the
global activity state of the system.
Context.POWER_SERVICE
("power")
PowerManager
for controlling power
management.
Context.ALARM_SERVICE
("alarm")
AlarmManager
for receiving intents at the
time of your choosing.
Context.NOTIFICATION_SERVICE
("notification")
NotificationManager
for informing the user
of background events.
Context.KEYGUARD_SERVICE
("keyguard")
KeyguardManager
for controlling keyguard.
Context.LOCATION_SERVICE
("location")
LocationManager
for controlling location
(e.g., GPS) updates.
Context.SEARCH_SERVICE
("search")
SearchManager
for handling search.
Context.VIBRATOR_SERVICE
("vibrator")
Vibrator
for interacting with the vibrator
hardware.
Context.CONNECTIVITY_SERVICE
("connection")
ConnectivityManager
for
handling management of network connections.
Context.WIFI_SERVICE
("wifi")
WifiManager
for management of Wi-Fi
connectivity. On releases before NYC, it should only be obtained from an application
context, and not from any other derived context to avoid memory leaks within the calling
process.
Context.WIFI_P2P_SERVICE
("wifip2p")
WifiP2pManager
for management of
Wi-Fi Direct connectivity.
Context.INPUT_METHOD_SERVICE
("input_method")
InputMethodManager
for management of input methods.
Context.UI_MODE_SERVICE
("uimode")
UiModeManager
for controlling UI modes.
Context.DOWNLOAD_SERVICE
("download")
DownloadManager
for requesting HTTP downloads
Context.BATTERY_SERVICE
("batterymanager")
BatteryManager
for managing battery state
Context.JOB_SCHEDULER_SERVICE
("taskmanager")
JobScheduler
for managing scheduled tasks
Context.NETWORK_STATS_SERVICE
("netstats")
NetworkStatsManager
for querying network
usage statistics.
Context.HARDWARE_PROPERTIES_SERVICE
("hardware_properties")
HardwarePropertiesManager
for accessing hardware properties.
Note: System services obtained via this API may be closely associated with the Context in which they are obtained from. In general, do not share the service objects between various different contexts (Activities, Applications, Services, Providers, etc.)
getSystemService
in class ContextThemeWrapper
name
- The name of the desired service.Context.WINDOW_SERVICE
,
WindowManager
,
Context.LAYOUT_INFLATER_SERVICE
,
LayoutInflater
,
Context.ACTIVITY_SERVICE
,
ActivityManager
,
Context.POWER_SERVICE
,
PowerManager
,
Context.ALARM_SERVICE
,
AlarmManager
,
Context.NOTIFICATION_SERVICE
,
NotificationManager
,
Context.KEYGUARD_SERVICE
,
KeyguardManager
,
Context.LOCATION_SERVICE
,
LocationManager
,
Context.SEARCH_SERVICE
,
SearchManager
,
Context.SENSOR_SERVICE
,
SensorManager
,
Context.STORAGE_SERVICE
,
StorageManager
,
Context.VIBRATOR_SERVICE
,
Vibrator
,
Context.CONNECTIVITY_SERVICE
,
ConnectivityManager
,
Context.WIFI_SERVICE
,
WifiManager
,
Context.AUDIO_SERVICE
,
AudioManager
,
Context.MEDIA_ROUTER_SERVICE
,
MediaRouter
,
Context.TELEPHONY_SERVICE
,
TelephonyManager
,
Context.TELEPHONY_SUBSCRIPTION_SERVICE
,
SubscriptionManager
,
Context.CARRIER_CONFIG_SERVICE
,
CarrierConfigManager
,
Context.INPUT_METHOD_SERVICE
,
InputMethodManager
,
Context.UI_MODE_SERVICE
,
UiModeManager
,
Context.DOWNLOAD_SERVICE
,
DownloadManager
,
Context.BATTERY_SERVICE
,
BatteryManager
,
Context.JOB_SCHEDULER_SERVICE
,
JobScheduler
,
Context.NETWORK_STATS_SERVICE
,
NetworkStatsManager
,
HardwarePropertiesManager
,
Context.HARDWARE_PROPERTIES_SERVICE
public void setTitle(CharSequence title)
public void setTitle(int titleId)
@Deprecated public void setTitleColor(int textColor)
This method is deprecated starting in API Level 11 and replaced by action bar styles. For information on styling the Action Bar, read the Action Bar developer guide.
public final CharSequence getTitle()
public final int getTitleColor()
protected void onTitleChanged(CharSequence title, int color)
protected void onChildTitleChanged(Activity childActivity, CharSequence title)
public void setTaskDescription(ActivityManager.TaskDescription taskDescription)
ActivityManager.getRecentTasks(int, int)
is called, the activities of each task
are traversed in order from the topmost activity to the bottommost. The traversal continues
for each property until a suitable value is found. For each task the taskDescription will be
returned in ActivityManager.TaskDescription
.taskDescription
- The TaskDescription properties that describe the task with this activityActivityManager.getRecentTasks(int, int)
,
ActivityManager.TaskDescription
@Deprecated public final void setProgressBarVisibility(boolean visible)
In order for the progress bar to be shown, the feature must be requested
via requestWindowFeature(int)
.
visible
- Whether to show the progress bars in the title.@Deprecated public final void setProgressBarIndeterminateVisibility(boolean visible)
In order for the progress bar to be shown, the feature must be requested
via requestWindowFeature(int)
.
visible
- Whether to show the progress bars in the title.@Deprecated public final void setProgressBarIndeterminate(boolean indeterminate)
In order for the progress bar to be shown, the feature must be requested
via requestWindowFeature(int)
.
indeterminate
- Whether the horizontal progress bar should be indeterminate.@Deprecated public final void setProgress(int progress)
In order for the progress bar to be shown, the feature must be requested
via requestWindowFeature(int)
.
progress
- The progress for the progress bar. Valid ranges are from
0 to 10000 (both inclusive). If 10000 is given, the progress
bar will be completely filled and will fade out.@Deprecated public final void setSecondaryProgress(int secondaryProgress)
setProgress(int)
and the background. It can be ideal for media
scenarios such as showing the buffering progress while the default
progress shows the play progress.
In order for the progress bar to be shown, the feature must be requested
via requestWindowFeature(int)
.
secondaryProgress
- The secondary progress for the progress bar. Valid ranges are from
0 to 10000 (both inclusive).public final void setVolumeControlStream(int streamType)
The suggested audio stream will be tied to the window of this Activity. Volume requests which are received while the Activity is in the foreground will affect this stream.
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
AudioManager.USE_DEFAULT_STREAM_TYPE
.
streamType
- The type of the audio stream whose volume should be
changed by the hardware volume controls.public final int getVolumeControlStream()
setVolumeControlStream(int)
public final void setMediaController(MediaController controller)
MediaController
to send media keys and volume changes to.
The controller will be tied to the window of this Activity. Media key and
volume events which are received while the Activity is in the foreground
will be forwarded to the controller and used to invoke transport controls
or adjust the volume. This may be used instead of or in addition to
setVolumeControlStream(int)
to affect a specific session instead of a
specific stream.
It is not guaranteed that the hardware volume controls will always change this session'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 null as the controller.
controller
- The controller for the session which should receive
media keys and volume changes.public final MediaController getMediaController()
setMediaController(android.media.session.MediaController)
public final void runOnUiThread(Runnable action)
action
- the action to run on the UI threadpublic View onCreateView(String name, Context context, AttributeSet attrs)
LayoutInflater.Factory.onCreateView(java.lang.String, android.content.Context, android.util.AttributeSet)
used when
inflating with the LayoutInflater returned by getSystemService(java.lang.String)
.
This implementation does nothing and is for
pre-Build.VERSION_CODES.HONEYCOMB
apps. Newer apps
should use onCreateView(View, String, Context, AttributeSet)
.onCreateView
in interface LayoutInflater.Factory
name
- Tag name to be inflated.context
- The context the view is being created in.attrs
- Inflation attributes as specified in XML file.LayoutInflater.createView(java.lang.String, java.lang.String, android.util.AttributeSet)
,
Window.getLayoutInflater()
public View onCreateView(View parent, String name, Context context, AttributeSet attrs)
LayoutInflater.Factory2.onCreateView(View, String, Context, AttributeSet)
used when inflating with the LayoutInflater returned by getSystemService(java.lang.String)
.
This implementation handles onCreateView
in interface LayoutInflater.Factory2
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.LayoutInflater.createView(java.lang.String, java.lang.String, android.util.AttributeSet)
,
Window.getLayoutInflater()
public void dump(String prefix, FileDescriptor fd, PrintWriter writer, String[] args)
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 boolean isImmersive()
android:immersive
but may be changed at runtime by
setImmersive(boolean)
.setImmersive(boolean)
,
ActivityInfo.FLAG_IMMERSIVE
public void convertFromTranslucent()
android.R.attr#windowIsTranslucent
to a
fullscreen opaque Activity.
Call this whenever the background of a translucent Activity has changed to become opaque.
Doing so will allow the Surface
of the Activity behind to be released.
This call has no effect on non-translucent activities or on activities with the
android.R.attr#windowIsFloating
attribute.
public boolean convertToTranslucent(Activity.TranslucentConversionListener callback, ActivityOptions options)
android.R.attr#windowIsTranslucent
back from
opaque to translucent following a call to convertFromTranslucent()
.
Calling this allows the Activity behind this one to be seen again. Once all such Activities
have been redrawn Activity.TranslucentConversionListener.onTranslucentConversionComplete(boolean)
will
be called indicating that it is safe to make this activity translucent again. Until
Activity.TranslucentConversionListener.onTranslucentConversionComplete(boolean)
is called the image
behind the frontmost Activity will be indeterminate.
This call has no effect on non-translucent activities or on activities with the
android.R.attr#windowIsFloating
attribute.
callback
- the method to call when all visible Activities behind this one have been
drawn and it is safe to make this Activity translucent again.options
- activity options delivered to the activity below this one. The options
are retrieved using getActivityOptions()
.true
if Window was opaque and will become translucent or
false
if window was translucent and no change needed to be made.convertFromTranslucent()
,
Activity.TranslucentConversionListener
public void onNewActivityOptions(ActivityOptions options)
public boolean requestVisibleBehind(boolean visible)
onResume()
and the return from
onPause()
. If this call is successful then the activity will remain visible after
onPause()
is called, and is allowed to continue playing media in the background.
The actions of this call are reset each time that this activity is brought to the
front. That is, every time onResume()
is called the activity will be assumed
to not have requested visible behind. Therefore, if you want this activity to continue to
be visible in the background you must call this method again.
Only fullscreen opaque activities may make this call. I.e. this call is a nop for dialog and translucent activities.
Under all circumstances, the activity must stop playing and release resources prior to or
within a call to onVisibleBehindCanceled()
or if this call returns false.
False will be returned any time this method is called between the return of onPause and the next call to onResume.
visible
- true to notify the system that the activity wishes to be visible behind other
translucent activities, false to indicate otherwise. Resources must be
released when passing false to this method.onPause()
if the next activity is translucent or not fullscreen. If false
then the activity may not count on being visible behind other translucent activities,
and must stop any media playback and release resources.
Returning false may occur in lieu of a call to onVisibleBehindCanceled()
so
the return value must be checked.onVisibleBehindCanceled()
public void onVisibleBehindCanceled()
super.onVisibleBehindCanceled()
or a SuperNotCalledException will be thrown.
When this method is called the activity has 500 msec to release any resources it may be
using while visible in the background.
If the activity has not returned from this method in 500 msec the system will destroy
the activity and kill the process in order to recover the resources for another
process. Otherwise onStop()
will be called following return.
requestVisibleBehind(boolean)
public boolean isBackgroundVisibleBehind()
requestVisibleBehind(boolean)
, false otherwise.requestVisibleBehind(boolean)
,
onVisibleBehindCanceled()
,
onBackgroundVisibleBehindChanged(boolean)
public void onBackgroundVisibleBehindChanged(boolean visible)
requestVisibleBehind(boolean)
or might be
due to a background activity finishing itself.visible
- true if a background activity is visible, false otherwise.requestVisibleBehind(boolean)
,
onVisibleBehindCanceled()
public void onEnterAnimationComplete()
public void dispatchEnterAnimationComplete()
public void setImmersive(boolean i)
ActivityInfo
structure; that is, if
android:immersive
is set to true
in the application's manifest entry for this activity, the ActivityInfo.flags
member will
always have its FLAG_IMMERSIVE
bit set.isImmersive()
,
ActivityInfo.FLAG_IMMERSIVE
public void setVrModeEnabled(boolean enabled, ComponentName requestedComponent) throws PackageManager.NameNotFoundException
VR mode is a hint to Android system to switch to a mode optimized for VR applications while this Activity has user focus.
It is recommended that applications additionally declare
android.R.attr#enableVrMode
in their manifest to allow for smooth activity
transitions when switching between VR activities.
If the requested VrListenerService
component is not available,
VR mode will not be started. Developers can handle this case as follows:
String servicePackage = "com.whatever.app"; String serviceClass = "com.whatever.app.MyVrListenerService"; // Name of the component of the VrListenerService to start. ComponentName serviceComponent = new ComponentName(servicePackage, serviceClass); try { setVrModeEnabled(true, myComponentName); } catch (PackageManager.NameNotFoundException e) { List<ApplicationInfo> installed = getPackageManager().getInstalledApplications(0); boolean isInstalled = false; for (ApplicationInfo app : installed) { if (app.packageName.equals(servicePackage)) { isInstalled = true; break; } } if (isInstalled) { // Package is installed, but not enabled in Settings. Let user enable it. startActivity(new Intent(Settings.ACTION_VR_LISTENER_SETTINGS)); } else { // Package is not installed. Send an intent to download this. sentIntentToLaunchAppStore(servicePackage); } }
enabled
- true
to enable this mode.requestedComponent
- the name of the component to use as a
VrListenerService
while VR mode is enabled.PackageManager.NameNotFoundException
- if the given component
to run as a VrListenerService
is not installed, or has
not been enabled in user settings.PackageManager.FEATURE_VR_MODE
,
PackageManager.FEATURE_VR_MODE_HIGH_PERFORMANCE
,
VrListenerService
,
Settings.ACTION_VR_LISTENER_SETTINGS
,
android.R.attr#enableVrMode
public ActionMode startActionMode(ActionMode.Callback callback)
ActionMode.TYPE_PRIMARY
.callback
- Callback that will manage lifecycle events for this action modeActionMode
public ActionMode startActionMode(ActionMode.Callback callback, int type)
callback
- Callback that will manage lifecycle events for this action modetype
- One of ActionMode.TYPE_PRIMARY
or ActionMode.TYPE_FLOATING
.ActionMode
public ActionMode onWindowStartingActionMode(ActionMode.Callback callback)
Note: If you are looking for a notification callback that an action mode
has been started for this activity, see onActionModeStarted(ActionMode)
.
onWindowStartingActionMode
in interface Window.Callback
callback
- The callback that should control the new action modenull
if the activity does not want to
provide special handling for this action mode. (It will be handled by the system.)public ActionMode onWindowStartingActionMode(ActionMode.Callback callback, int type)
onWindowStartingActionMode
in interface Window.Callback
callback
- Callback to control the lifecycle of this action modetype
- One of ActionMode.TYPE_PRIMARY
or ActionMode.TYPE_FLOATING
.public void onActionModeStarted(ActionMode mode)
onActionModeStarted
in interface Window.Callback
mode
- The new action mode.public void onActionModeFinished(ActionMode mode)
onActionModeFinished
in interface Window.Callback
mode
- The action mode that just finished.public boolean shouldUpRecreateTask(Intent targetIntent)
If this method returns false the app can trivially call
navigateUpTo(Intent)
using the same parameters to correctly perform
up navigation. If this method returns false, the app should synthesize a new task stack
by using TaskStackBuilder
or another similar mechanism to perform up navigation.
targetIntent
- An intent representing the target destination for up navigationpublic boolean navigateUpTo(Intent upIntent)
If the indicated activity does not appear in the history stack, this will finish each activity in this task until the root activity of the task is reached, resulting in an "in-app home" behavior. This can be useful in apps with a complex navigation hierarchy when an activity may be reached by a path not passing through a canonical parent activity.
This method should be used when performing up navigation from within the same task
as the destination. If up navigation should cross tasks in some cases, see
shouldUpRecreateTask(Intent)
.
upIntent
- An intent representing the target destination for up navigationpublic boolean navigateUpToFromChild(Activity child, Intent upIntent)
navigateUpTo(android.content.Intent)
method. The default implementation simply calls
navigateUpTo(upIntent) on this activity (the parent).child
- The activity making the call.upIntent
- An intent representing the target destination for up navigationpublic Intent getParentActivityIntent()
Intent
that will launch an explicit target activity specified by
this activity's logical parent. The logical parent is named in the application's manifest
by the parentActivityName
attribute.
Activity subclasses may override this method to modify the Intent returned by
super.getParentActivityIntent() or to implement a different mechanism of retrieving
the parent intent entirely.public void setEnterSharedElementCallback(SharedElementCallback callback)
ActivityOptions.makeSceneTransitionAnimation(Activity,
android.view.View, String)
was used to start an Activity, callback
will be called to handle shared elements on the launched Activity. This requires
Window.FEATURE_ACTIVITY_TRANSITIONS
.callback
- Used to manipulate shared element transitions on the launched Activity.public void setExitSharedElementCallback(SharedElementCallback callback)
ActivityOptions.makeSceneTransitionAnimation(Activity,
android.view.View, String)
was used to start an Activity, callback
will be called to handle shared elements on the launching Activity. Most
calls will only come when returning from the started Activity.
This requires Window.FEATURE_ACTIVITY_TRANSITIONS
.callback
- Used to manipulate shared element transitions on the launching Activity.public void postponeEnterTransition()
ActivityOptions.makeSceneTransitionAnimation(Activity,
android.util.Pair[])
.
This method gives the Activity the ability to delay starting the entering and
shared element transitions until all data is loaded. Until then, the Activity won't
draw into its window, leaving the window transparent. This may also cause the
returning animation to be delayed until data is ready. This method should be
called in onCreate(android.os.Bundle)
or in
onActivityReenter(int, android.content.Intent)
.
startPostponedEnterTransition()
must be called to allow the Activity to
start the transitions. If the Activity did not use
ActivityOptions.makeSceneTransitionAnimation(Activity,
android.util.Pair[])
, then this method does nothing.
public void startPostponedEnterTransition()
postponeEnterTransition()
was called.
If postponeEnterTransition() was called, you must call startPostponedEnterTransition()
to have your Activity start drawing.public DragAndDropPermissions requestDragAndDropPermissions(DragEvent event)
DragAndDropPermissions
object bound to this activity and controlling the
access permissions for content URIs associated with the DragEvent
.event
- Drag eventDragAndDropPermissions
object used to control access to the content URIs.
Null if no content URIs are associated with the event or if permissions could not be granted.public final IBinder getActivityToken()
public final boolean isResumed()
public void startLockTask()
android.R.attr#lockTaskMode
values permit launching while locked.
If DevicePolicyManager.isLockTaskPermitted(String)
returns true or
lockTaskMode=lockTaskModeAlways for this component then the app will go directly into
Lock Task mode. The user will not be able to exit this mode until
stopLockTask()
is called.
If DevicePolicyManager.isLockTaskPermitted(String)
returns false
then the system will prompt the user with a dialog requesting permission to enter
this mode. When entered through this method the user can exit at any time through
an action described by the request dialog. Calling stopLockTask will also exit the
mode.android.R.attr#lockTaskMode
public void stopLockTask()
startLockTask()
. This
can only be called by activities that have successfully called
startLockTask previously.
This will allow the user to exit this app and move onto other activities.
Note: This method should only be called when the activity is user-facing. That is, between onResume() and onPause().
Note: If there are other tasks below this one that are also locked then calling this method will immediately finish this task and resume the previous locked one, remaining in lockTask mode.
android.R.attr#lockTaskMode
,
ActivityManager.getLockTaskModeState()
public void showLockTaskEscapeMessage()
public boolean isOverlayWithDecorCaptionEnabled()
#setOverlayWithDecorCaptionEnabled(boolean)}
public void setOverlayWithDecorCaptionEnabled(boolean enabled)