Activity
open class Activity : ContextThemeWrapper, ComponentCallbacks2, KeyEvent.Callback, LayoutInflater.Factory2, View.OnCreateContextMenuListener, Window.Callback
kotlin.Any | ||||
↳ | android.content.Context | |||
↳ | android.content.ContextWrapper | |||
↳ | android.view.ContextThemeWrapper | |||
↳ | android.app.Activity |
An activity is a single, focused thing that the user can do. Almost all activities interact with the user, so the Activity class takes care of creating a window for you in which you can place your UI with #setContentView. 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), Multi-Window mode or embedded into other windows. There are two methods almost all subclasses of Activity will implement:
- #onCreate is where you initialize your activity. Most importantly, here you will usually call
setContentView(int)
with a layout resource defining your UI, and usingfindViewById
to retrieve the widgets in that UI that you need to interact with programmatically. -
onPause
is where you deal with the user pausing active interaction with the activity. Any changes made by the user should at this point be committed (usually to theandroid.content.ContentProvider
holding the data). In this state the activity is still visible on screen.
To be of use with android.content.Context#startActivity, all activity classes must have a corresponding <activity>
declaration in their package's AndroidManifest.xml
.
Topics covered here:
- Fragments
- Activity Lifecycle
- Configuration Changes
- Starting Activities and Getting Results
- Saving Persistent State
- Permissions
- Process Lifecycle
Fragments
The androidx.fragment.app.FragmentActivity subclass can make use of the androidx.fragment.app.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.
For more information about using fragments, read the Fragments developer guide.
Activity Lifecycle
Activities in the system are managed as activity stacks. When a new activity is started, it is usually placed on the top of the current 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. There can be one or multiple activity stacks visible on screen.
An activity has essentially four states:
- If an activity is in the foreground of the screen (at the highest position of the topmost stack), it is active or running. This is usually the activity that the user is currently interacting with.
- If an activity has lost focus but is still presented to the user, it is visible. It is possible if a new non-full-sized or transparent activity has focus on top of your activity, another activity has higher position in multi-window mode, or the activity itself is not focusable in current windowing mode. Such activity is completely alive (it maintains all state and member information and remains attached to the window manager).
- If an activity is completely obscured by another activity, it is stopped or hidden. It still retains all state and member information, however, it is no longer visible to the user so its window is hidden and it will often be killed by the system when memory is needed elsewhere.
- The system can drop the activity from memory by either asking it to finish, or simply killing its process, making it destroyed. When it is displayed again to the user, it must be completely restarted and restored to its previous state.
The following diagram shows the important state paths of an activity. The square rectangles represent callback methods you can implement to perform operations when the activity moves between states. The colored ovals are major states the activity can be in.
There are three key loops you may be interested in monitoring within your activity:
- The entire lifetime of an activity happens between the first call to android.app.Activity#onCreate through to a single final call to
android.app.Activity#onDestroy
. An activity will do all setup of "global" state in onCreate(), and release all remaining resources in onDestroy(). For example, if it has a thread running in the background to download data from the network, it may create that thread in onCreate() and then stop the thread in onDestroy(). - The visible lifetime of an activity happens between a call to
android.app.Activity#onStart
until a corresponding call toandroid.app.Activity#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 aandroid.content.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. - The foreground lifetime of an activity happens between a call to
android.app.Activity#onResume
until a corresponding call toandroid.app.Activity#onPause
. During this time the activity is visible, active 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 android.app.Activity#onCreate to do their initial setup; many will also implement android.app.Activity#onPause
to commit changes to data and prepare to pause interacting with the user, and android.app.Activity#onStop
to handle no longer being visible on screen. 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 | ||
---|---|---|---|---|---|
android.app.Activity#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 its activity stack, with user input going to it.
Always followed by |
No | onPause() |
||
onPause() |
Called when the activity loses foreground state, is no longer focusable or before transition to stopped/hidden or destroyed state. The activity is still visible to user, so it's recommended to keep it visually active and continue updating the UI. Implementations of this method must be very quick because the next activity will not be resumed until this method returns.
Followed by either |
Pre-android.os.Build.VERSION_CODES#HONEYCOMB |
onResume() oronStop() |
||
onStop() |
Called when the activity is no longer visible to the user. This may happen either because a new activity is being started on top, an existing one is being brought in front of this one, or this one is being destroyed. This is typically used to stop animations and refreshing the UI, etc.
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 Activity.finish on it), or because the system is temporarily destroying this instance of the activity to save space. You can distinguish between these two scenarios with the android.app.Activity#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(android.os.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 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 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 android.os.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(android.os.Bundle)
may be called (it may be safely called after onPause()
) and allows an application to safely wait until onStop()
to save persistent state.
For applications targeting platforms starting with android.os.Build.VERSION_CODES#P
onSaveInstanceState(android.os.Bundle)
will always be called after onStop
, so an application may safely perform fragment transactions in onStop
and will be able to save persistent state later.
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 onStop()
to the start of onResume()
. Keep in mind that under extreme memory pressure the system can kill the application process at any time.
Configuration Changes
If the configuration of the device (as defined by the Resources.Configuration
class) changes, then anything displaying a user interface will need to update to match that configuration. Because Activity is the primary mechanism for interacting with the user, it includes special support for handling configuration changes.
Unless you specify otherwise, a configuration change (such as a change in screen orientation, language, input devices, etc.) will cause your current activity to be destroyed, going through the normal activity lifecycle process of onPause
, onStop
, and onDestroy
as appropriate. If the activity had been in the foreground or visible to the user, once onDestroy
is called in that instance then a new instance of the activity will be created, with whatever savedInstanceState the previous instance had generated from #onSaveInstanceState.
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
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
will not be called.
Starting Activities and Getting Results
The android.app.Activity#startActivity 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 android.app.Activity#startActivityForResult(Intent, int)
version with a second integer parameter identifying the call. The result will come back through your android.app.Activity#onActivityResult method.
When an activity exits, it can call android.app.Activity#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)); } } } }
Saving Persistent State
There are generally two kinds of persistent state that 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 an "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 email, a new entry for that email is created as soon as they start entering data, so that if they go to any other activity after that point this email 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 stopped (or paused on platform versions before android.os.Build.VERSION_CODES#HONEYCOMB
). 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
, 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); mPrefs = getSharedPreferences(getLocalClassName(), MODE_PRIVATE); mCurViewMode = mPrefs.getInt("view_mode", DAY_VIEW_MODE); } protected void onPause() { super.onPause(); SharedPreferences.Editor ed = mPrefs.edit(); ed.putInt("view_mode", mCurViewMode); ed.commit(); } }
Permissions
The ability to start a particular Activity can be enforced when it is declared in its manifest's <activity>
tag. By doing so, other applications will need to declare a corresponding <uses-permission>
element in their own manifest to be able to start that activity.
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 android.os.Build.VERSION_CODES#GINGERBREAD
, if the Activity was already created and a new Intent is being delivered to onNewIntent(android.content.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.
Process Lifecycle
The Android system attempts to keep an 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 or next to other activities in multi-window mode) 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 stopped) 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 method will be called with the savedInstanceState it had previously supplied in #onSaveInstanceState 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
orandroid.content.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.
Summary
Nested classes | |
---|---|
abstract |
Interface for observing screen captures of an |
Constants | |
---|---|
static Int |
Use with |
static Int |
Use with |
static Int |
Use with |
static Int |
Use with |
static Int |
Use with |
static Int |
Request type of |
static Int |
Request type of |
static Int |
Request type of |
static Int |
Request type of |
static Int |
Standard activity result: operation canceled. |
static Int |
Start of user-defined activity results. |
static Int |
Standard activity result: operation succeeded. |
Inherited constants | |
---|---|
Public constructors | |
---|---|
Activity() |
Public methods | |
---|---|
open Unit |
addContentView(view: View!, params: ViewGroup.LayoutParams!) Add an additional content view to the activity. |
open Unit |
clearOverrideActivityTransition(overrideType: Int) Clears the animations which are set from #overrideActivityTransition. |
open Unit |
Programmatically closes the most recently opened context menu, if showing. |
open Unit |
Progammatically closes the options menu. |
open PendingIntent! |
createPendingResult(requestCode: Int, data: Intent, flags: Int) Create a new PendingIntent object which you can hand to others for them to use to send result data back to your #onActivityResult callback. |
Unit |
dismissDialog(id: Int) Dismiss a dialog that was previously shown via |
Unit |
Dismiss the Keyboard Shortcuts screen. |
open Boolean |
Called to process generic motion events. |
open Boolean |
dispatchKeyEvent(event: KeyEvent!) Called to process key events. |
open Boolean |
dispatchKeyShortcutEvent(event: KeyEvent!) Called to process a key shortcut event. |
open Boolean | |
open Boolean |
Called to process touch screen events. |
open Boolean |
Called to process trackball events. |
open Unit |
dump(prefix: String, fd: FileDescriptor?, writer: PrintWriter, args: Array<String!>?) Print the Activity's state into the given stream. |
open Unit |
Puts the activity in picture-in-picture mode if possible in the current system state. |
open Boolean |
Puts the activity in picture-in-picture mode if possible in the current system state. |
open T |
findViewById(id: Int) Finds a view that was identified by the |
open Unit |
finish() Call this when your activity is done and should be closed. |
open Unit |
finishActivity(requestCode: Int) Force finish another activity that you had previously started with #startActivityForResult. |
open Unit |
finishActivityFromChild(child: Activity, requestCode: Int) This is called when a child activity of this one calls its finishActivity(). |
open Unit |
Finish this activity as well as all activities immediately below it in the current task that have the same affinity. |
open Unit |
Reverses the Activity Scene entry Transition and triggers the calling Activity to reverse its exit Transition. |
open Unit |
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. |
open Unit |
finishFromChild(child: Activity!) This is called when a child activity of this one calls its |
open ActionBar? |
Retrieve a reference to this activity's ActionBar. |
Application! |
Return the application that owns this activity. |
open ComponentCaller? |
Returns the ComponentCaller instance of the app that started this activity. |
open ComponentName? |
Return the name of the activity that invoked this activity. |
open String? |
Return the name of the package that invoked this activity. |
open Int |
If this activity is being destroyed because it can not handle a configuration parameter being changed (and thus its |
open ComponentName! |
Returns the complete component name of this activity. |
open Scene! |
Retrieve the |
open TransitionManager! |
Retrieve the |
open ComponentCaller |
Returns the ComponentCaller instance of the app that re-launched this activity with a new intent via #onNewIntent or #onActivityResult. |
open View? |
Calls |
open FragmentManager! |
Return the FragmentManager for interacting with fragments associated with this activity. |
open ComponentCaller |
Returns the ComponentCaller instance of the app that initially launched this activity. |
open Intent! |
Returns the intent that started this activity. |
open Any? |
Retrieve the non-configuration instance data that was previously returned by |
open String? |
Returns the package name of the app that initially launched this activity. |
open Int |
Returns the uid of the app that initially launched this activity. |
open LayoutInflater |
Convenience for calling |
open LoaderManager! |
Return the LoaderManager for this activity, creating it if needed. |
open String |
Returns class name for this activity with the package prefix removed. |
open Int |
Return the number of actions that will be displayed in the picture-in-picture UI when the user interacts with the activity currently in picture-in-picture mode. |
MediaController! |
Gets the controller which should be receiving media key and volume events while this activity is in the foreground. |
open MenuInflater |
Returns a |
open OnBackInvokedDispatcher |
Returns the |
Activity! |
Returns the parent |
open Intent? |
Obtain an |
open SharedPreferences! |
getPreferences(mode: Int) Retrieve a |
open Uri? |
Return information about who launched this activity. |
open Int |
Return the current requested orientation of the activity. |
SearchEvent! |
During the onSearchRequested() callbacks, this function will return the |
SplashScreen |
Get the interface that activity use to talk to the splash screen. |
open Any! |
getSystemService(name: String) Return the handle to a system-level service by name. |
open Int |
Return the identifier of the task this activity is in. |
CharSequence! |
getTitle() |
Int | |
open VoiceInteractor! |
Retrieve the active |
Int |
Gets the suggested audio stream whose volume should be changed by the hardware volume controls. |
open Window! |
Retrieve the current |
open WindowManager! |
Retrieve the window manager for showing custom windows. |
open Boolean |
Returns true if this activity's main window currently has window focus. |
open Unit |
Declare that the options menu has changed, so should be recreated. |
open Boolean |
Returns whether there are any activity transitions currently running on this activity. |
open Boolean |
Check to see whether this activity is in the process of being destroyed in order to be recreated with a new configuration. |
Boolean |
isChild() Whether this is a child |
open Boolean |
Returns true if the final |
open Boolean |
Check to see whether this activity is in the process of finishing, either because you called |
open Boolean |
Bit indicating that this activity is "immersive" and should not be interrupted by notifications if possible. |
open Boolean |
Returns true if the activity is currently in multi-window mode. |
open Boolean |
Returns true if the activity is currently in picture-in-picture mode. |
open Boolean |
Indicates whether this activity is launched from a bubble. |
open Boolean |
Queries whether the currently enabled voice interaction service supports returning a voice interactor for use by the activity. |
open Boolean |
Return whether this activity is the root of a task. |
open Boolean |
Check whether this activity is running as part of a voice interaction with the user. |
open Boolean |
Like |
Cursor! |
managedQuery(uri: Uri!, projection: Array<String!>!, selection: String!, selectionArgs: Array<String!>!, sortOrder: String!) Wrapper around |
open Boolean |
moveTaskToBack(nonRoot: Boolean) Move the task containing this activity to the back of the activity stack. |
open Boolean |
navigateUpTo(: Intent!) Navigate from this activity to the activity specified by upIntent, finishing this activity in the process. |
open Boolean |
navigateUpToFromChild(: Activity!, : Intent!) This is called when a child activity of this one calls its |
open Unit |
onActionModeFinished(mode: ActionMode!) Notifies the activity that an action mode has finished. |
open Unit |
onActionModeStarted(mode: ActionMode!) Notifies the Activity that an action mode has been started. |
open Unit |
onActivityReenter(resultCode: Int, data: Intent!) 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. |
open Unit |
onActivityResult(requestCode: Int, resultCode: Int, data: Intent?, caller: ComponentCaller) Same as |
open Unit |
onAttachFragment(fragment: Fragment!) Called when a Fragment is being attached to this activity, immediately after the call to its android. |
open Unit |
Called when the main window associated with the activity has been attached to the window manager. |
open Unit |
Called when the activity has detected the user's press of the back key. |
open Unit |
onConfigurationChanged(newConfig: Configuration) Called by the system when the device configuration changes while your activity is running. |
open Unit | |
open Boolean |
onContextItemSelected(item: MenuItem) This hook is called whenever an item in a context menu is selected. |
open Unit |
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). |
open Unit |
onCreate(savedInstanceState: Bundle?, persistentState: PersistableBundle?) Same as |
open Unit |
onCreateContextMenu(: ContextMenu!, v: View!, : ContextMenu.ContextMenuInfo!) Called when a context menu for the |
open CharSequence? |
Generate a new description for this activity. |
open Unit |
Define the synthetic task stack that will be generated during Up navigation from a different task. |
open Boolean |
Initialize the contents of the Activity's standard options menu. |
open Boolean |
onCreatePanelMenu(featureId: Int, : Menu) Default implementation of |
open View? |
onCreatePanelView(featureId: Int) Default implementation of |
open Boolean |
onCreateThumbnail(outBitmap: Bitmap!, canvas: Canvas!) |
open View? |
onCreateView(parent: View?, name: String, context: Context, attrs: AttributeSet) Standard implementation of |
open View? |
onCreateView(name: String, context: Context, attrs: AttributeSet) Standard implementation of |
open Unit |
Called when the main window associated with the activity has been detached from the window manager. |
open Unit |
Activities cannot draw during the period that their windows are animating in. |
open Boolean |
onGenericMotionEvent(event: MotionEvent!) Called when a generic motion event was not handled by any of the views inside of the activity. |
open Unit |
onGetDirectActions(cancellationSignal: CancellationSignal, callback: Consumer<MutableList<DirectAction!>!>) Returns the list of direct actions supported by the app. |
open Boolean |
Called when a key was pressed down and not handled by any of the views inside of the activity. |
open Boolean |
onKeyLongPress(keyCode: Int, event: KeyEvent!) Default implementation of |
open Boolean |
onKeyMultiple(keyCode: Int, repeatCount: Int, event: KeyEvent!) Default implementation of |
open Boolean |
onKeyShortcut(keyCode: Int, event: KeyEvent!) Called when a key shortcut event is not handled by any of the views in the Activity. |
open Boolean |
Called when a key was released and not handled by any of the views inside of the activity. |
open Unit |
Callback to indicate that |
open Unit |
Callback to indicate that the local voice interaction has stopped either because it was requested through a call to |
open Unit | |
open Boolean |
onMenuItemSelected(featureId: Int, item: MenuItem) Default implementation of |
open Boolean |
onMenuOpened(featureId: Int, : Menu) Called when a panel's menu is opened by the user. |
open Unit |
onMultiWindowModeChanged(isInMultiWindowMode: Boolean) Called by the system when the activity changes from fullscreen mode to multi-window mode and visa-versa. |
open Unit |
onMultiWindowModeChanged(isInMultiWindowMode: Boolean, newConfig: Configuration!) Called by the system when the activity changes from fullscreen mode to multi-window mode and visa-versa. |
open Boolean |
This method is called whenever the user chooses to navigate Up within your application's activity hierarchy from the action bar. |
open Boolean |
This is called when a child activity of this one attempts to navigate up. |
open Unit |
onNewIntent(intent: Intent, caller: ComponentCaller) Same as |
open Boolean |
onOptionsItemSelected(item: MenuItem) This hook is called whenever an item in your options menu is selected. |
open Unit |
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). |
open Unit |
onPanelClosed(featureId: Int, : Menu) Default implementation of |
open Unit |
onPerformDirectAction(actionId: String, arguments: Bundle, cancellationSignal: CancellationSignal, resultListener: Consumer<Bundle!>) This is called to perform an action previously defined by the app. |
open Unit |
onPictureInPictureModeChanged(isInPictureInPictureMode: Boolean) Called by the system when the activity changes to and from picture-in-picture mode. |
open Unit |
onPictureInPictureModeChanged(isInPictureInPictureMode: Boolean, newConfig: Configuration!) Called by the system when the activity changes to and from picture-in-picture mode. |
open Boolean |
This method is called by the system in various cases where picture in picture mode should be entered if supported. |
open Unit |
Called by the system when the activity is in PiP and has state changes. |
open Unit |
onPostCreate(savedInstanceState: Bundle?, persistentState: PersistableBundle?) This is the same as |
open Unit |
Prepare the synthetic task stack that will be generated during Up navigation from a different task. |
open Boolean |
Prepare the Screen's standard options menu to be displayed. |
open Boolean |
onPreparePanel(featureId: Int, view: View?, : Menu) Default implementation of |
open Unit |
onProvideAssistContent(outContent: AssistContent!) This is called when the user is requesting an assist, to provide references to content related to the current activity. |
open Unit |
onProvideAssistData(data: Bundle!) This is called when the user is requesting an assist, to build a full |
open Unit |
onProvideKeyboardShortcuts(data: MutableList<KeyboardShortcutGroup!>!, : Menu?, deviceId: Int) |
open Uri! |
Override to generate the desired referrer for the content currently being shown by the app. |
open Unit |
onRequestPermissionsResult(requestCode: Int, permissions: Array<String!>, grantResults: IntArray) Callback for the result from requesting permissions. |
open Unit |
onRequestPermissionsResult(requestCode: Int, permissions: Array<String!>, grantResults: IntArray, deviceId: Int) Callback for the result from requesting permissions. |
open Unit |
onRestoreInstanceState(savedInstanceState: Bundle?, persistentState: PersistableBundle?) This is the same as |
open Any! |
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. |
open Unit |
onSaveInstanceState(outState: Bundle, outPersistentState: PersistableBundle) This is the same as #onSaveInstanceState but is called for activities created with the attribute |
open Boolean | |
open Boolean |
onSearchRequested(searchEvent: SearchEvent?) This hook is called when the user signals the desire to start a search. |
open Unit |
Called when an |
open Unit |
onTopResumedActivityChanged(isTopResumedActivity: Boolean) Called when activity gets or loses the top resumed position in the system. |
open Boolean |
onTouchEvent(event: MotionEvent!) Called when a touch screen event was not handled by any of the views inside of the activity. |
open Boolean |
onTrackballEvent(event: MotionEvent!) Called when the trackball was moved and not handled by any of the views inside of the activity. |
open Unit |
onTrimMemory(level: Int) |
open Unit |
Called whenever a key, touch, or trackball event is dispatched to the activity. |
open Unit |
Called when a translucent activity over this activity is becoming opaque or another activity is being launched. |
open Unit | |
open Unit |
onWindowFocusChanged(hasFocus: Boolean) Called when the current |
open ActionMode? |
onWindowStartingActionMode(callback: ActionMode.Callback!) Give the Activity a chance to control the UI for an action mode requested by the system. |
open ActionMode? |
onWindowStartingActionMode(callback: ActionMode.Callback!, type: Int) Called when an action mode is being started for this window. |
open Unit |
openContextMenu(view: View!) Programmatically opens the context menu for a particular |
open Unit |
Programmatically opens the options menu. |
open Unit |
overrideActivityTransition(overrideType: Int, enterAnim: Int, exitAnim: Int) Customizes the animation for the activity transition with this activity. |
open Unit |
overrideActivityTransition(overrideType: Int, enterAnim: Int, exitAnim: Int, backgroundColor: Int) Customizes the animation for the activity transition with this activity. |
open Unit |
overridePendingTransition(enterAnim: Int, exitAnim: Int) Call immediately after one of the flavors of #startActivity(android.content.Intent) or |
open Unit |
overridePendingTransition(enterAnim: Int, exitAnim: Int, backgroundColor: Int) Call immediately after one of the flavors of #startActivity(android.content.Intent) or |
open Unit |
Postpone the entering activity transition when Activity was started with |
open Unit |
recreate() Cause this Activity to be recreated with a new instance. |
open Unit |
Register an |
open Unit |
registerComponentCallbacks(callback: ComponentCallbacks!) |
open Unit |
registerForContextMenu(view: View!) Registers a context menu to be shown for the given view (multiple views can show the context menu). |
open Unit |
registerScreenCaptureCallback(executor: Executor, callback: Activity.ScreenCaptureCallback) Registers a screen capture callback for this activity. |
open Boolean |
Ask that the local app instance of this activity be released to free up its memory. |
Unit |
removeDialog(id: Int) Removes any internal references to a dialog managed by this Activity. |
open Unit |
Report to the system that your app is now fully drawn, for diagnostic and optimization purposes. |
open DragAndDropPermissions! |
requestDragAndDropPermissions(event: DragEvent!) Create |
open Unit |
requestFullscreenMode(request: Int, approvalCallback: OutcomeReceiver<Void!, Throwable!>?) Request to put the activity into fullscreen. |
Unit |
Requests to show the “Open in browser” education. |
Unit |
requestPermissions(permissions: Array<String!>, requestCode: Int) Requests permissions to be granted to this application. |
Unit |
requestPermissions(permissions: Array<String!>, requestCode: Int, deviceId: Int) Requests permissions to be granted to this application. |
Unit |
Request the Keyboard Shortcuts screen to show up. |
open Boolean |
requestVisibleBehind(visible: Boolean) Activities that want to remain visible behind a translucent activity above them must call this method anytime between the start of |
Boolean |
requestWindowFeature(featureId: Int) Enable extended window features. |
T |
requireViewById(id: Int) Finds a view that was identified by the |
Unit |
runOnUiThread(action: Runnable!) Runs the specified action on the UI thread. |
open Unit |
setActionBar(toolbar: Toolbar?) Set a |
open Unit |
Specifies whether the activities below this one in the task can also start other activities or finish the task. |
open Unit |
Set the |
open Unit |
setContentView(view: View!) Set the activity content to an explicit view. |
open Unit |
setContentView(view: View!, params: ViewGroup.LayoutParams!) Set the activity content to an explicit view. |
open Unit |
setContentView(layoutResID: Int) Set the activity content from a layout resource. |
Unit |
setDefaultKeyMode(mode: Int) Select the default key handling for this activity. |
open Unit |
When |
open Unit |
When |
Unit |
setFeatureDrawable(featureId: Int, drawable: Drawable!) Convenience for calling |
Unit |
setFeatureDrawableAlpha(featureId: Int, alpha: Int) Convenience for calling |
Unit |
setFeatureDrawableResource(featureId: Int, resId: Int) Convenience for calling |
Unit |
setFeatureDrawableUri(featureId: Int, uri: Uri!) Convenience for calling |
open Unit |
setFinishOnTouchOutside(finish: Boolean) Sets whether this activity is finished when touched outside its window's bounds. |
open Unit |
setImmersive(i: Boolean) Adjust the current immersive mode setting. |
open Unit |
setInheritShowWhenLocked(inheritShowWhenLocked: Boolean) Specifies whether this |
open Unit |
Changes the intent returned by |
open Unit |
setIntent(newIntent: Intent?, newCaller: ComponentCaller?) Changes the intent returned by |
open Unit |
setLocusContext(locusId: LocusId?, bundle: Bundle?) Sets the |
Unit |
setMediaController(controller: MediaController!) Sets a |
open Unit |
Updates the properties of the picture-in-picture activity, or sets it to be used later when |
Unit |
setProgress(progress: Int) Sets the progress for the progress bars in the title. |
Unit |
setProgressBarIndeterminate(indeterminate: Boolean) Sets whether the horizontal progress bar in the title should be indeterminate (the circular is always indeterminate). |
Unit |
setProgressBarIndeterminateVisibility(visible: Boolean) Sets the visibility of the indeterminate progress bar in the title. |
Unit |
setProgressBarVisibility(visible: Boolean) Sets the visibility of the progress bar in the title. |
open Unit |
setRecentsScreenshotEnabled(enabled: Boolean) If set to false, this indicates to the system that it should never take a screenshot of the activity to be used as a representation in recents screen. |
open Unit |
setRequestedOrientation(requestedOrientation: Int) Change the desired orientation of this activity. |
Unit |
Call this to set the result that your activity will return to its caller. |
Unit |
Call this to set the result that your activity will return to its caller. |
Unit |
setSecondaryProgress(secondaryProgress: Int) Sets the secondary progress for the progress bar in the title. |
open Unit |
setShouldDockBigOverlays(shouldDockBigOverlays: Boolean) Specifies a preference to dock big overlays like the expanded picture-in-picture on TV (see |
open Unit |
setShowWhenLocked(showWhenLocked: Boolean) Specifies whether an |
open Unit |
setTaskDescription(taskDescription: ActivityManager.TaskDescription!) Sets information describing the task with this activity for presentation inside the Recents System UI. |
open Unit | |
open Unit |
Change the title associated with this activity. |
open Unit |
setTitle(title: CharSequence!) Change the title associated with this activity. |
open Unit |
setTitleColor(textColor: Int) Change the color of the title associated with this activity. |
open Boolean |
setTranslucent(translucent: Boolean) Convert an activity, which particularly with |
open Unit |
setTurnScreenOn(turnScreenOn: Boolean) Specifies whether the screen should be turned on when the |
open Unit |
setVisible(visible: Boolean) Control whether this activity's main window is visible. |
Unit |
setVolumeControlStream(streamType: Int) Suggests an audio stream whose volume should be changed by the hardware volume controls. |
open Unit |
setVrModeEnabled(enabled: Boolean, requestedComponent: ComponentName) Enable or disable virtual reality (VR) mode for this Activity. |
open Boolean |
Returns whether big overlays should be docked next to the activity as set by |
open Boolean |
shouldShowRequestPermissionRationale(permission: String) Gets whether you should show UI with rationale before requesting a permission. |
open Boolean |
shouldShowRequestPermissionRationale(permission: String, deviceId: Int) Gets whether you should show UI with rationale before requesting a permission. |
open Boolean |
shouldUpRecreateTask(targetIntent: Intent!) Returns true if the app should recreate the task when navigating 'up' from this activity by using targetIntent. |
open Boolean |
showAssist(args: Bundle!) Ask to have the current assistant shown to the user. |
Unit |
showDialog(id: Int) Simple version of |
Boolean |
showDialog(id: Int, args: Bundle!) Show a dialog managed by this activity. |
open Unit |
Shows the user the system defined message for telling the user how to exit lock task mode. |
open ActionMode? |
startActionMode(callback: ActionMode.Callback!) Start an action mode of the default type |
open ActionMode? |
startActionMode(callback: ActionMode.Callback!, type: Int) Start an action mode of the given type. |
open Unit |
startActivities(intents: Array<Intent!>!) Same as #startActivities(android.content.Intent[],android.os.Bundle) with no options specified. |
open Unit |
startActivities(intents: Array<Intent!>!, options: Bundle?) Launch a new activity. |
open Unit |
startActivity(intent: Intent!) Same as #startActivity(android.content.Intent,android.os.Bundle) with no options specified. |
open Unit |
startActivity(intent: Intent!, options: Bundle?) Launch a new activity. |
open Unit |
startActivityForResult(intent: Intent!, requestCode: Int) Same as calling |
open Unit |
startActivityForResult(intent: Intent!, requestCode: Int, options: Bundle?) Launch an activity for which you would like a result when it finished. |
open Unit |
startActivityFromChild(child: Activity, intent: Intent!, requestCode: Int) Same as calling |
open Unit |
startActivityFromChild(child: Activity, intent: Intent!, requestCode: Int, options: Bundle?) This is called when a child activity of this one calls its #startActivity or #startActivityForResult method. |
open Unit |
startActivityFromFragment(fragment: Fragment, intent: Intent!, requestCode: Int) Same as calling |
open Unit |
startActivityFromFragment(fragment: Fragment, intent: Intent!, requestCode: Int, options: Bundle?) This is called when a Fragment in this activity calls its android. |
open Boolean |
startActivityIfNeeded(intent: Intent, requestCode: Int) Same as calling |
open Boolean |
startActivityIfNeeded(intent: Intent, requestCode: Int, options: Bundle?) A special variation to launch an activity only if a new activity instance is needed to handle the given Intent. |
open Unit |
startIntentSender(intent: IntentSender!, fillInIntent: Intent?, flagsMask: Int, flagsValues: Int, extraFlags: Int) Same as calling #startIntentSender(android.content.IntentSender,android.content.Intent,int,int,int,android.os.Bundle) with no options. |
open Unit |
startIntentSender(intent: IntentSender!, fillInIntent: Intent?, flagsMask: Int, flagsValues: Int, extraFlags: Int, options: Bundle?) Like #startActivity(android.content.Intent,android.os.Bundle), but taking a IntentSender to start; see |
open Unit |
startIntentSenderForResult(intent: IntentSender!, requestCode: Int, fillInIntent: Intent?, flagsMask: Int, flagsValues: Int, extraFlags: Int) Same as calling |
open Unit |
startIntentSenderForResult(intent: IntentSender!, requestCode: Int, fillInIntent: Intent?, flagsMask: Int, flagsValues: Int, extraFlags: Int, options: Bundle?) Like |
open Unit |
startIntentSenderFromChild(child: Activity!, intent: IntentSender!, requestCode: Int, fillInIntent: Intent!, flagsMask: Int, flagsValues: Int, extraFlags: Int) Same as calling |
open Unit |
startIntentSenderFromChild(child: Activity!, intent: IntentSender!, requestCode: Int, fillInIntent: Intent!, flagsMask: Int, flagsValues: Int, extraFlags: Int, options: Bundle?) Like |
open Unit |
startLocalVoiceInteraction(privateOptions: Bundle!) Starts a local voice interaction session. |
open Unit |
Request to put this activity in a mode where the user is locked to a restricted set of applications. |
open Unit |
This method allows the activity to take care of managing the given |
open Boolean |
startNextMatchingActivity(intent: Intent) Same as calling |
open Boolean |
startNextMatchingActivity(intent: Intent, options: Bundle?) Special version of starting an activity, for use when you are replacing other activity components. |
open Unit |
Begin postponed transitions after |
open Unit |
startSearch(initialQuery: String?, selectInitialQuery: Boolean, appSearchData: Bundle?, globalSearch: Boolean) This hook is called to launch the search UI. |
open Unit |
Request to terminate the current voice interaction that was previously started using |
open Unit |
Stop the current task from being locked. |
open Unit |
stopManagingCursor(c: Cursor!) Given a Cursor that was previously given to |
open Unit |
takeKeyEvents(get: Boolean) Request that key events come to this activity. |
open Unit |
triggerSearch(query: String!, appSearchData: Bundle?) Similar to |
open Unit |
Unregister an |
open Unit |
unregisterComponentCallbacks(callback: ComponentCallbacks!) |
open Unit |
unregisterForContextMenu(view: View!) Prevents a context menu to be shown for the given view. |
open Unit |
Unregisters a screen capture callback for this surface. |
Protected methods | |
---|---|
open Unit |
attachBaseContext(newBase: Context!) |
open Unit |
onActivityResult(requestCode: Int, resultCode: Int, data: Intent!) 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. |
open Unit |
onApplyThemeResource(theme: Resources.Theme!, resid: Int, first: Boolean) |
open Unit |
onChildTitleChanged(childActivity: Activity!, title: CharSequence!) |
open Unit |
Called when the activity is starting. |
open Dialog! |
onCreateDialog(id: Int) |
open Dialog? |
onCreateDialog(id: Int, args: Bundle!) Callback for creating dialogs that are managed (saved and restored) for you by the activity. |
open Unit |
Perform any final cleanup before an activity is destroyed. |
open Unit |
onNewIntent(intent: Intent!) This is called for activities that set launchMode to "singleTop" in their package, or if a client used the |
open Unit |
onPause() Called as part of the activity lifecycle when the user no longer actively interacts with the activity, but it is still visible on screen. |
open Unit |
onPostCreate(savedInstanceState: Bundle?) Called when activity start-up is complete (after |
open Unit |
Called when activity resume is complete (after |
open Unit |
onPrepareDialog(id: Int, dialog: Dialog!) |
open Unit |
onPrepareDialog(id: Int, dialog: Dialog!, args: Bundle!) Provides an opportunity to prepare a managed dialog before it is being shown. |
open Unit |
Called after |
open Unit |
onRestoreInstanceState(savedInstanceState: Bundle) This method is called after |
open Unit |
onResume() Called after #onRestoreInstanceState, |
open Unit |
onSaveInstanceState(outState: Bundle) Called to retrieve per-instance state from an activity before being killed so that the state can be restored in #onCreate or #onRestoreInstanceState (the |
open Unit |
onStart() Called after #onCreate — or after |
open Unit |
onStop() Called when you are no longer visible to the user. |
open Unit |
onTitleChanged(title: CharSequence!, color: Int) |
open Unit |
Called as part of the activity lifecycle when an activity is about to go into the background as the result of user choice. |
Inherited functions | |
---|---|
Properties | |
---|---|
static IntArray! |
Constants
DEFAULT_KEYS_DIALER
static val DEFAULT_KEYS_DIALER: Int
Use with setDefaultKeyMode
to launch the dialer during default key handling.
Value: 1
See Also
DEFAULT_KEYS_DISABLE
static val DEFAULT_KEYS_DISABLE: Int
Use with setDefaultKeyMode
to turn off default handling of keys.
Value: 0
See Also
DEFAULT_KEYS_SEARCH_GLOBAL
static val DEFAULT_KEYS_SEARCH_GLOBAL: Int
Use with setDefaultKeyMode
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.
Value: 4
See Also
DEFAULT_KEYS_SEARCH_LOCAL
static val DEFAULT_KEYS_SEARCH_LOCAL: Int
Use with setDefaultKeyMode
to specify that unhandled keystrokes will start an application-defined search. (If the application or activity does not actually define a search, the keys will be ignored.)
See android.app.SearchManager
for more details.
Value: 3
See Also
DEFAULT_KEYS_SHORTCUT
static val DEFAULT_KEYS_SHORTCUT: Int
Use with setDefaultKeyMode
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.
Value: 2
See Also
FULLSCREEN_MODE_REQUEST_ENTER
static val FULLSCREEN_MODE_REQUEST_ENTER: Int
Request type of requestFullscreenMode(int,android.os.OutcomeReceiver)
, to request enter fullscreen mode from multi-window mode.
Value: 1
FULLSCREEN_MODE_REQUEST_EXIT
static val FULLSCREEN_MODE_REQUEST_EXIT: Int
Request type of requestFullscreenMode(int,android.os.OutcomeReceiver)
, to request exiting the requested fullscreen mode and restore to the previous multi-window mode.
Value: 0
OVERRIDE_TRANSITION_CLOSE
static val OVERRIDE_TRANSITION_CLOSE: Int
Request type of overrideActivityTransition(int,int,int)
or overrideActivityTransition(int,int,int,int)
, to override the closing transition.
Value: 1
OVERRIDE_TRANSITION_OPEN
static val OVERRIDE_TRANSITION_OPEN: Int
Request type of overrideActivityTransition(int,int,int)
or overrideActivityTransition(int,int,int,int)
, to override the opening transition.
Value: 0
RESULT_CANCELED
static val RESULT_CANCELED: Int
Standard activity result: operation canceled.
Value: 0
RESULT_FIRST_USER
static val RESULT_FIRST_USER: Int
Start of user-defined activity results.
Value: 1
RESULT_OK
static val RESULT_OK: Int
Standard activity result: operation succeeded.
Value: -1
Public constructors
Activity
Activity()
Public methods
addContentView
open fun addContentView(
view: View!,
params: ViewGroup.LayoutParams!
): Unit
Add an additional content view to the activity. Added after any existing ones in the activity -- existing views are NOT removed.
Parameters | |
---|---|
view |
View!: The desired content to display. |
params |
ViewGroup.LayoutParams!: Layout parameters for the view. |
clearOverrideActivityTransition
open fun clearOverrideActivityTransition(overrideType: Int): Unit
Clears the animations which are set from #overrideActivityTransition.
Parameters | |
---|---|
overrideType |
Int: OVERRIDE_TRANSITION_OPEN clear the animation set for starting a new activity. OVERRIDE_TRANSITION_CLOSE clear the animation set for finishing an activity. Value is android.app.Activity#OVERRIDE_TRANSITION_OPEN , or android.app.Activity#OVERRIDE_TRANSITION_CLOSE |
closeContextMenu
open fun closeContextMenu(): Unit
Programmatically closes the most recently opened context menu, if showing.
closeOptionsMenu
open fun closeOptionsMenu(): Unit
Progammatically closes the options menu. If the options menu is already closed, this method does nothing.
createPendingResult
open fun createPendingResult(
requestCode: Int,
data: Intent,
flags: Int
): PendingIntent!
Create a new PendingIntent object which you can hand to others for them to use to send result data back to your #onActivityResult 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).
Return | |
---|---|
PendingIntent! |
Returns an existing or new PendingIntent matching the given parameters. May return null only if PendingIntent.FLAG_NO_CREATE has been supplied. |
See Also
dismissDialog
fundismissDialog(id: Int): Unit
Deprecated: Use the new DialogFragment
class with FragmentManager
instead; this is also available on older platforms through the Android compatibility package.
Dismiss a dialog that was previously shown via showDialog(int)
.
Parameters | |
---|---|
id |
Int: The id of the managed dialog. |
Exceptions | |
---|---|
java.lang.IllegalArgumentException |
if the id was not previously shown via showDialog(int) . |
dismissKeyboardShortcutsHelper
fun dismissKeyboardShortcutsHelper(): Unit
Dismiss the Keyboard Shortcuts screen.
dispatchGenericMotionEvent
open fun dispatchGenericMotionEvent(ev: MotionEvent!): Boolean
Called to process generic motion events. You can override this to intercept all generic motion events before they are dispatched to the window. Be sure to call this implementation for generic motion events that should be handled normally.
Parameters | |
---|---|
event |
The generic motion event. |
ev |
MotionEvent!: The generic motion event. |
Return | |
---|---|
Boolean |
boolean Return true if this event was consumed. |
See Also
dispatchKeyEvent
open fun dispatchKeyEvent(event: KeyEvent!): Boolean
Called to process key events. You can override this to intercept all key events before they are dispatched to the window. Be sure to call this implementation for key events that should be handled normally.
Parameters | |
---|---|
event |
KeyEvent!: The key event. |
Return | |
---|---|
Boolean |
boolean Return true if this event was consumed. |
dispatchKeyShortcutEvent
open fun dispatchKeyShortcutEvent(event: KeyEvent!): Boolean
Called to process a key shortcut event. You can override this to intercept all key shortcut events before they are dispatched to the window. Be sure to call this implementation for key shortcut events that should be handled normally.
Parameters | |
---|---|
event |
KeyEvent!: The key shortcut event. |
Return | |
---|---|
Boolean |
True if this event was consumed. |
dispatchPopulateAccessibilityEvent
open fun dispatchPopulateAccessibilityEvent(event: AccessibilityEvent!): Boolean
Parameters | |
---|---|
event |
AccessibilityEvent!: The event. |
Return | |
---|---|
Boolean |
boolean Return true if event population was completed. |
dispatchTouchEvent
open fun dispatchTouchEvent(ev: MotionEvent!): Boolean
Called to process touch screen events. You can override this to intercept all touch screen events before they are dispatched to the window. Be sure to call this implementation for touch screen events that should be handled normally.
Parameters | |
---|---|
event |
The touch screen event. |
ev |
MotionEvent!: The touch screen event. |
Return | |
---|---|
Boolean |
boolean Return true if this event was consumed. |
See Also
dispatchTrackballEvent
open fun dispatchTrackballEvent(ev: MotionEvent!): Boolean
Called to process trackball events. You can override this to intercept all trackball events before they are dispatched to the window. Be sure to call this implementation for trackball events that should be handled normally.
Parameters | |
---|---|
event |
The trackball event. |
ev |
MotionEvent!: The trackball event. |
Return | |
---|---|
Boolean |
boolean Return true if this event was consumed. |
See Also
dump
open fun dump(
prefix: String,
fd: FileDescriptor?,
writer: PrintWriter,
args: Array<String!>?
): Unit
Print the Activity's state into the given stream. This gets invoked if you run adb shell dumpsys activity <activity_component_name>
.
This method won't be called if the app targets android.os.Build.VERSION_CODES#TIRAMISU
or later if the dump request starts with one of the following arguments:
- --autofill
- --contentcapture
- --translation
- --list-dumpables
- --dump-dumpable
Parameters | |
---|---|
prefix |
String: Desired prefix to prepend at each line of output. This value cannot be null . |
fd |
FileDescriptor?: The raw file descriptor that the dump is being sent to. This value may be null . |
writer |
PrintWriter: The PrintWriter to which you should dump your state. This will be closed for you after you return. This value cannot be null . |
args |
Array<String!>?: additional arguments to the dump request. This value may be null . |
enterPictureInPictureMode
open funenterPictureInPictureMode(): Unit
Deprecated: Deprecated in Java.
Puts the activity in picture-in-picture mode if possible in the current system state. Any prior calls to setPictureInPictureParams(android.app.PictureInPictureParams)
will still apply when entering picture-in-picture through this call.
enterPictureInPictureMode
open fun enterPictureInPictureMode(params: PictureInPictureParams): Boolean
Puts the activity in picture-in-picture mode if possible in the current system state. The set parameters in {@param params} will be combined with the parameters from prior calls to setPictureInPictureParams(android.app.PictureInPictureParams)
. The system may disallow entering picture-in-picture in various cases, including when the activity is not visible, if the screen is locked or if the user has an activity pinned.
By default, system calculates the dimension of picture-in-picture window based on the given {@param params}. See Picture-in-picture Support on how to override this behavior.
Parameters | |
---|---|
params |
PictureInPictureParams: non-null parameters to be combined with previously set parameters when entering picture-in-picture. |
Return | |
---|---|
Boolean |
true if the system successfully put this activity into picture-in-picture mode or was already in picture-in-picture mode (see isInPictureInPictureMode() ). If the device does not support picture-in-picture, return false. |
findViewById
open fun <T : View!> findViewById(id: Int): T
Finds a view that was identified by the android:id
XML attribute that was processed in #onCreate.
Note: In most cases -- depending on compiler support -- the resulting view is automatically cast to the target class type. If the target class type is unconstrained, an explicit cast may be necessary.
Parameters | |
---|---|
id |
Int: the ID to search for |
Return | |
---|---|
T |
a view with given ID if found, or null otherwise |
finish
open fun finish(): Unit
Call this when your activity is done and should be closed. The ActivityResult is propagated back to whoever launched you via onActivityResult().
finishActivity
open fun finishActivity(requestCode: Int): Unit
Force finish another activity that you had previously started with #startActivityForResult.
Parameters | |
---|---|
requestCode |
Int: 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. |
finishActivityFromChild
open funfinishActivityFromChild(
child: Activity,
requestCode: Int
): Unit
Deprecated: Use finishActivity(int)
instead.
This is called when a child activity of this one calls its finishActivity().
Parameters | |
---|---|
child |
Activity: The activity making the call. This value cannot be null . |
requestCode |
Int: Request code that had been used to start the activity. |
finishAffinity
open fun finishAffinity(): Unit
Finish this activity as well as all activities immediately below it in the current task that have the same affinity. This is typically used when an application can be launched on to another task (such as from an ACTION_VIEW of a content type it understands) and the user has used the up navigation to switch out of the current task and in to its own task. In this case, if the user has navigated down into any other activities of the second application, all of those should be removed from the original task as part of the task switch.
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.
finishAfterTransition
open fun finishAfterTransition(): Unit
Reverses the Activity Scene entry Transition and triggers the calling Activity to reverse its exit Transition. When the exit Transition completes, finish()
is called. If no entry Transition was used, finish() is called immediately and the Activity exit Transition is run.
finishAndRemoveTask
open fun finishAndRemoveTask(): Unit
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.
finishFromChild
open funfinishFromChild(child: Activity!): Unit
Deprecated: Use finish()
instead.
This is called when a child activity of this one calls its finish
method. The default implementation simply calls finish() on this activity (the parent), finishing the entire group.
Parameters | |
---|---|
child |
Activity!: The activity making the call. |
See Also
getActionBar
open fun getActionBar(): ActionBar?
Retrieve a reference to this activity's ActionBar.
Return | |
---|---|
ActionBar? |
The Activity's ActionBar, or null if it does not have one. |
getApplication
fun getApplication(): Application!
Return the application that owns this activity.
getCaller
open fun getCaller(): ComponentCaller?
Returns the ComponentCaller instance of the app that started this activity.
To keep the ComponentCaller instance for future use, call setIntent(android.content.Intent,android.app.ComponentCaller)
, and use this method to retrieve it.
Note that in #onNewIntent, this method will return the original ComponentCaller. You can use setIntent(android.content.Intent,android.app.ComponentCaller)
to update it to the new ComponentCaller.
Return | |
---|---|
ComponentCaller? |
ComponentCaller instance corresponding to the intent from getIntent() , or null if the activity was not launched with that intent |
getCallingActivity
open fun getCallingActivity(): ComponentName?
Return the name of the activity that invoked this activity. This is who the data in #setResult will be sent to. You can use this information to validate that the recipient is allowed to receive the data.
Note: if the calling activity is not expecting a result (that is it did not use the #startActivityForResult form that includes a request code), then the calling package will be null.
Return | |
---|---|
ComponentName? |
The ComponentName of the activity that will receive your reply, or null if none. |
getCallingPackage
open fun getCallingPackage(): String?
Return the name of the package that invoked this activity. This is who the data in #setResult will be sent to. You can use this information to validate that the recipient is allowed to receive the data.
Note: if the calling activity is not expecting a result (that is it did not use the #startActivityForResult form that includes a request code), then the calling package will be null.
Note: prior to android.os.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.
Return | |
---|---|
String? |
The package of the activity that will receive your reply, or null if none. |
getChangingConfigurations
open fun getChangingConfigurations(): Int
If this activity is being destroyed because it can not handle a configuration parameter being changed (and thus its onConfigurationChanged(android.content.res.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.
Return | |
---|---|
Int |
Returns a bit field of the configuration parameters that are changing, as defined by the android.content.res.Configuration class. |
getComponentName
open fun getComponentName(): ComponentName!
Returns the complete component name of this activity.
Return | |
---|---|
ComponentName! |
Returns the complete component name for this activity |
getContentScene
open fun getContentScene(): Scene!
Retrieve the 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.
Return | |
---|---|
Scene! |
Current Scene being shown or null |
getContentTransitionManager
open fun getContentTransitionManager(): TransitionManager!
Retrieve the 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) if Window.FEATURE_CONTENT_TRANSITIONS
has been granted.
Return | |
---|---|
TransitionManager! |
This window's content TransitionManager or null if none is set. |
getCurrentCaller
open fun getCurrentCaller(): ComponentCaller
Returns the ComponentCaller instance of the app that re-launched this activity with a new intent via #onNewIntent or #onActivityResult.
Note that this method only works within the #onNewIntent and #onActivityResult methods. If you call this method outside #onNewIntent and #onActivityResult, it will throw an IllegalStateException
.
You can also retrieve the caller if you override onNewIntent(android.content.Intent,android.app.ComponentCaller)
or onActivityResult(int,int,android.content.Intent,android.app.ComponentCaller)
.
To keep the ComponentCaller instance for future use, call setIntent(android.content.Intent,android.app.ComponentCaller)
, and use getCaller
to retrieve it.
Return | |
---|---|
ComponentCaller |
ComponentCaller instance This value cannot be null . |
Exceptions | |
---|---|
java.lang.IllegalStateException |
if the caller is null , indicating the method was called outside #onNewIntent |
getCurrentFocus
open fun getCurrentFocus(): View?
Calls android.view.Window#getCurrentFocus
on the Window of this Activity to return the currently focused view.
Return | |
---|---|
View? |
View The current View with focus or null. |
getFragmentManager
open fungetFragmentManager(): FragmentManager!
Deprecated: Use androidx.fragment.app.FragmentActivity#getSupportFragmentManager()
Return the FragmentManager for interacting with fragments associated with this activity.
getInitialCaller
open fun getInitialCaller(): ComponentCaller
Returns the ComponentCaller instance of the app that initially launched this activity.
Note that calls to #onNewIntent and #setIntent have no effect on the returned value of this method.
Return | |
---|---|
ComponentCaller |
ComponentCaller instance This value cannot be null . |
See Also
getIntent
open fun getIntent(): Intent!
Returns the intent that started this activity.
To keep the Intent instance for future use, call setIntent(android.content.Intent)
, and use this method to retrieve it.
Note that in #onNewIntent, this method will return the original Intent. You can use setIntent(android.content.Intent)
to update it to the new Intent.
Return | |
---|---|
Intent! |
Intent instance that started this activity, or that was kept for future use |
getLastNonConfigurationInstance
open fun getLastNonConfigurationInstance(): Any?
Retrieve the non-configuration instance data that was previously returned by onRetainNonConfigurationInstance()
. This will be available from the initial #onCreate 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(android.os.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.
Return | |
---|---|
Any? |
the object previously returned by onRetainNonConfigurationInstance() |
getLaunchedFromPackage
open fun getLaunchedFromPackage(): String?
Returns the package name of the app that initially launched this activity.
In order to receive the launching app's package name, at least one of the following has to be met:
- The app must call
ActivityOptions.setShareIdentityEnabled(boolean)
with a value oftrue
and launch this activity with the resultingActivityOptions
. - The launched activity has the same uid as the launching app.
- The launched activity is running in a package that is signed with the same key used to sign the platform (typically only system packages such as Settings will meet this requirement).
getLaunchedFromUid()
; if any of these are met, then these methods can be used to obtain the uid and package name of the launching app. If none are met, then null
is returned.
Note, even if the above conditions are not met, the launching app's identity may still be available from getCallingPackage()
if this activity was started with Activity#startActivityForResult
to allow validation of the result's recipient.
Return | |
---|---|
String? |
the package name of the launching app or null if the current activity cannot access the identity of the launching app |
getLaunchedFromUid
open fun getLaunchedFromUid(): Int
Returns the uid of the app that initially launched this activity.
In order to receive the launching app's uid, at least one of the following has to be met:
- The app must call
ActivityOptions.setShareIdentityEnabled(boolean)
with a value oftrue
and launch this activity with the resultingActivityOptions
. - The launched activity has the same uid as the launching app.
- The launched activity is running in a package that is signed with the same key used to sign the platform (typically only system packages such as Settings will meet this requirement).
getLaunchedFromPackage()
; if any of these are met, then these methods can be used to obtain the uid and package name of the launching app. If none are met, then Process.INVALID_UID
is returned.
Note, even if the above conditions are not met, the launching app's identity may still be available from getCallingPackage()
if this activity was started with Activity#startActivityForResult
to allow validation of the result's recipient.
Return | |
---|---|
Int |
the uid of the launching app or Process.INVALID_UID if the current activity cannot access the identity of the launching app |
getLayoutInflater
open fun getLayoutInflater(): LayoutInflater
Convenience for calling android.view.Window#getLayoutInflater
.
Return | |
---|---|
LayoutInflater |
This value cannot be null . |
getLoaderManager
open fungetLoaderManager(): LoaderManager!
Deprecated: Use androidx.fragment.app.FragmentActivity#getSupportLoaderManager()
Return the LoaderManager for this activity, creating it if needed.
getLocalClassName
open fun getLocalClassName(): String
Returns class name for this activity with the package prefix removed. This is the default name used to read and write settings.
Return | |
---|---|
String |
The local class name. This value cannot be null . |
getMaxNumPictureInPictureActions
open fun getMaxNumPictureInPictureActions(): Int
Return the number of actions that will be displayed in the picture-in-picture UI when the user interacts with the activity currently in picture-in-picture mode. This number may change if the global configuration changes (ie. if the device is plugged into an external display), but will always be at least three.
getMediaController
fun getMediaController(): MediaController!
Gets the controller which should be receiving media key and volume events while this activity is in the foreground.
Return | |
---|---|
MediaController! |
The controller which should receive events. |
getMenuInflater
open fun getMenuInflater(): MenuInflater
Returns a MenuInflater
with this context.
Return | |
---|---|
MenuInflater |
This value cannot be null . |
getOnBackInvokedDispatcher
open fun getOnBackInvokedDispatcher(): OnBackInvokedDispatcher
Returns the OnBackInvokedDispatcher
instance associated with the window that this activity is attached to.
Return | |
---|---|
OnBackInvokedDispatcher |
This value cannot be null . |
Exceptions | |
---|---|
java.lang.IllegalStateException |
if this Activity is not visual. |
getParent
fungetParent(): Activity!
Deprecated: ActivityGroup
is deprecated.
Returns the parent Activity
if this is a child Activity
of an ActivityGroup
.
getParentActivityIntent
open fun getParentActivityIntent(): Intent?
Obtain an 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.
Return | |
---|---|
Intent? |
a new Intent targeting the defined parent of this activity or null if there is no valid parent. |
getPreferences
open fun getPreferences(mode: Int): SharedPreferences!
Retrieve a SharedPreferences
object for accessing preferences that are private to this activity. This simply calls the underlying getSharedPreferences(java.lang.String,int)
method by passing in this activity's class name as the preferences name.
Parameters | |
---|---|
mode |
Int: Operating mode. Use MODE_PRIVATE for the default operation. Value is either 0 or a combination of android.content.Context#MODE_PRIVATE , android.content.Context#MODE_WORLD_READABLE , android.content.Context#MODE_WORLD_WRITEABLE , and android.content.Context#MODE_MULTI_PROCESS |
Return | |
---|---|
SharedPreferences! |
Returns the single SharedPreferences instance that can be used to retrieve and modify the preference values. |
getReferrer
open fun getReferrer(): Uri?
Return information about who launched this activity. If the launching Intent contains an 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, this function will return the referrer that submitted that new intent to the activity only after setIntent(android.content.Intent)
is called with the provided intent.
Note that this is not a security feature -- you can not trust the referrer information, applications can spoof it.
getRequestedOrientation
open fun getRequestedOrientation(): Int
Return the current requested orientation of the activity. This is either the orientation requested in the app manifest, or the last requested orientation given to setRequestedOrientation(int)
. Note:
- Device manufacturers can configure devices to ignore calls to this method to improve the layout of orientation-restricted apps.
- On devices with Android 16 (API level 36) or higher installed, virtual device owners (limited to select trusted and privileged apps) can optimize app layout on displays they manage by ignoring calls to this method. See also Companion app streaming.
See Device compatibility mode.
getSearchEvent
fun getSearchEvent(): SearchEvent!
During the onSearchRequested() callbacks, this function will return the SearchEvent
that triggered the callback, if it exists.
Return | |
---|---|
SearchEvent! |
SearchEvent The SearchEvent that triggered the #onSearchRequested callback. |
getSplashScreen
fun getSplashScreen(): SplashScreen
Get the interface that activity use to talk to the splash screen.
Return | |
---|---|
SplashScreen |
This value cannot be null . |
See Also
getSystemService
open fun getSystemService(name: String): Any!
Return the handle to a system-level service by name. The class of the returned object varies by the requested name. Currently available names are:
-
WINDOW_SERVICE
("window") - The top-level window manager in which you can place custom windows. The returned object is a
android.view.WindowManager
. Must only be obtained from a visual context such as Activity or a Context created withcreateWindowContext(int,android.os.Bundle)
, which are adjusted to the configuration and visual bounds of an area on screen. -
LAYOUT_INFLATER_SERVICE
("layout_inflater") - A
android.view.LayoutInflater
for inflating layout resources in this context. Must only be obtained from a visual context such as Activity or a Context created withcreateWindowContext(int,android.os.Bundle)
, which are adjusted to the configuration and visual bounds of an area on screen. -
ACTIVITY_SERVICE
("activity") - A
android.app.ActivityManager
for interacting with the global activity state of the system. -
WALLPAPER_SERVICE
("wallpaper") - A
android.service.wallpaper.WallpaperService
for accessing wallpapers in this context. Must only be obtained from a visual context such as Activity or a Context created withcreateWindowContext(int,android.os.Bundle)
, which are adjusted to the configuration and visual bounds of an area on screen. -
POWER_SERVICE
("power") - A
android.os.PowerManager
for controlling power management. -
ALARM_SERVICE
("alarm") - A
android.app.AlarmManager
for receiving intents at the time of your choosing. -
NOTIFICATION_SERVICE
("notification") - A
android.app.NotificationManager
for informing the user of background events. -
KEYGUARD_SERVICE
("keyguard") - A
android.app.KeyguardManager
for controlling keyguard. -
LOCATION_SERVICE
("location") - A
android.location.LocationManager
for controlling location (e.g., GPS) updates. -
SEARCH_SERVICE
("search") - A
android.app.SearchManager
for handling search. -
VIBRATOR_MANAGER_SERVICE
("vibrator_manager") - A
android.os.VibratorManager
for accessing the device vibrators, interacting with individual ones and playing synchronized effects on multiple vibrators. -
VIBRATOR_SERVICE
("vibrator") - A
android.os.Vibrator
for interacting with the vibrator hardware. -
CONNECTIVITY_SERVICE
("connectivity") - A
ConnectivityManager
for handling management of network connections. -
IPSEC_SERVICE
("ipsec") - A
IpSecManager
for managing IPSec on sockets and networks. -
WIFI_SERVICE
("wifi") - A
WifiManager
for management of Wi-Fi connectivity. On releases before Android 7, it should only be obtained from an application context, and not from any other derived context to avoid memory leaks within the calling process. -
WIFI_AWARE_SERVICE
("wifiaware") - A
WifiAwareManager
for management of Wi-Fi Aware discovery and connectivity. -
WIFI_P2P_SERVICE
("wifip2p") - A
WifiP2pManager
for management of Wi-Fi Direct connectivity. -
INPUT_METHOD_SERVICE
("input_method") - An
InputMethodManager
for management of input methods. -
UI_MODE_SERVICE
("uimode") - An
android.app.UiModeManager
for controlling UI modes. -
DOWNLOAD_SERVICE
("download") - A
android.app.DownloadManager
for requesting HTTP downloads -
BATTERY_SERVICE
("batterymanager") - A
android.os.BatteryManager
for managing battery state -
JOB_SCHEDULER_SERVICE
("taskmanager") - A
android.app.job.JobScheduler
for managing scheduled tasks -
NETWORK_STATS_SERVICE
("netstats") - A
NetworkStatsManager
for querying network usage statistics. -
HARDWARE_PROPERTIES_SERVICE
("hardware_properties") - A
android.os.HardwarePropertiesManager
for accessing hardware properties. -
DOMAIN_VERIFICATION_SERVICE
("domain_verification") - A
android.content.pm.verify.domain.DomainVerificationManager
for accessing web domain approval state. -
DISPLAY_HASH_SERVICE
("display_hash") - A
android.view.displayhash.DisplayHashManager
for management of display hashes. - #AUTHENTICATION_POLICY_SERVICE ("authentication_policy")
- A
android.security.authenticationpolicy.AuthenticationPolicyManager
for managing authentication related policies on the device.
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.)
Note: Instant apps, for which PackageManager.isInstantApp()
returns true, don't have access to the following system services: DEVICE_POLICY_SERVICE
, FINGERPRINT_SERVICE
, KEYGUARD_SERVICE
, SHORTCUT_SERVICE
, USB_SERVICE
, WALLPAPER_SERVICE
, WIFI_P2P_SERVICE
, WIFI_SERVICE
, WIFI_AWARE_SERVICE
. For these services this method will return null
. Generally, if you are running as an instant app you should always check whether the result of this method is null
.
Note: When implementing this method, keep in mind that new services can be added on newer Android releases, so if you're looking for just the explicit names mentioned above, make sure to return null
when you don't recognize the name — if you throw a RuntimeException
exception instead, your app might break on new Android releases.
Return | |
---|---|
Any! |
The service or null if the name does not exist. |
getTaskId
open fun getTaskId(): Int
Return the identifier of the task this activity is in. This identifier will remain the same for the lifetime of the activity.
Return | |
---|---|
Int |
Task identifier, an opaque integer. |
getVoiceInteractor
open fun getVoiceInteractor(): VoiceInteractor!
Retrieve the active VoiceInteractor
that the user is going through to interact with this activity.
getVolumeControlStream
fun getVolumeControlStream(): Int
Gets the suggested audio stream whose volume should be changed by the hardware volume controls.
Return | |
---|---|
Int |
The suggested audio stream type whose volume should be changed by the hardware volume controls. |
See Also
getWindow
open fun getWindow(): Window!
Retrieve the current android.view.Window
for the activity. This can be used to directly access parts of the Window API that are not available through Activity/Screen.
Return | |
---|---|
Window! |
Window The current window, or null if the activity is not visual. |
getWindowManager
open fun getWindowManager(): WindowManager!
Retrieve the window manager for showing custom windows.
hasWindowFocus
open fun hasWindowFocus(): Boolean
Returns true if this activity's main window currently has window focus. Note that this is not the same as the view itself having focus.
Return | |
---|---|
Boolean |
True if this activity's main window currently has window focus. |
invalidateOptionsMenu
open fun invalidateOptionsMenu(): Unit
Declare that the options menu has changed, so should be recreated. The onCreateOptionsMenu(android.view.Menu)
method will be called the next time it needs to be displayed.
isActivityTransitionRunning
open fun isActivityTransitionRunning(): Boolean
Returns whether there are any activity transitions currently running on this activity. A return value of true
can mean that either an enter or exit transition is running, including whether the background of the activity is animating as a part of that transition.
Return | |
---|---|
Boolean |
true if a transition is currently running on this activity, false otherwise. |
isChangingConfigurations
open fun isChangingConfigurations(): Boolean
Check to see whether this activity is in the process of being destroyed in order to be recreated with a new configuration. This is often used in onStop
to determine whether the state needs to be cleaned up or will be passed on to the next instance of the activity via onRetainNonConfigurationInstance()
.
Return | |
---|---|
Boolean |
If the activity is being torn down in order to be recreated with a new configuration, returns true; else returns false. |
isChild
funisChild(): Boolean
Deprecated: ActivityGroup
is deprecated.
Whether this is a child Activity
of an ActivityGroup
.
isDestroyed
open fun isDestroyed(): Boolean
Returns true if the final onDestroy()
call has been made on the Activity, so this instance is now dead.
isFinishing
open fun isFinishing(): Boolean
Check to see whether this activity is in the process of finishing, either because you called finish
on it or someone else has requested that it finished. This is often used in onPause
to determine whether the activity is simply pausing or completely finishing.
Return | |
---|---|
Boolean |
If the activity is finishing, returns true; else returns false. |
See Also
isImmersive
open fun isImmersive(): Boolean
Bit indicating that this activity is "immersive" and should not be interrupted by notifications if possible. This value is initially set by the manifest property android:immersive
but may be changed at runtime by setImmersive
.
isInMultiWindowMode
open fun isInMultiWindowMode(): Boolean
Returns true if the activity is currently in multi-window mode.
Return | |
---|---|
Boolean |
True if the activity is in multi-window mode. |
See Also
isInPictureInPictureMode
open fun isInPictureInPictureMode(): Boolean
Returns true if the activity is currently in picture-in-picture mode.
Return | |
---|---|
Boolean |
True if the activity is in picture-in-picture mode. |
isLaunchedFromBubble
open fun isLaunchedFromBubble(): Boolean
Indicates whether this activity is launched from a bubble. A bubble is a floating shortcut on the screen that expands to show an activity. If your activity can be used normally or as a bubble, you might use this method to check if the activity is bubbled to modify any behaviour that might be different between the normal activity and the bubbled activity. For example, if you normally cancel the notification associated with the activity when you open the activity, you might not want to do that when you're bubbled as that would remove the bubble.
Return | |
---|---|
Boolean |
true if the activity is launched from a bubble. |
isLocalVoiceInteractionSupported
open fun isLocalVoiceInteractionSupported(): Boolean
Queries whether the currently enabled voice interaction service supports returning a voice interactor for use by the activity. This is valid only for the duration of the activity.
Return | |
---|---|
Boolean |
whether the current voice interaction service supports local voice interaction |
isTaskRoot
open fun isTaskRoot(): Boolean
Return whether this activity is the root of a task. The root is the first activity in a task.
Return | |
---|---|
Boolean |
True if this is the root activity, else false. |
isVoiceInteraction
open fun isVoiceInteraction(): Boolean
Check whether this activity is running as part of a voice interaction with the user. If true, it should perform its interaction with the user through the VoiceInteractor
returned by getVoiceInteractor
.
isVoiceInteractionRoot
open fun isVoiceInteractionRoot(): Boolean
Like 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
. If the activity launchMode
is singleTask
, it forces the activity to launch in a new task, separate from the one that started it. Therefore, there is no longer a relationship between them, and isVoiceInteractionRoot()
return false
in this case.
managedQuery
funmanagedQuery(
uri: Uri!,
projection: Array<String!>!,
selection: String!,
selectionArgs: Array<String!>!,
sortOrder: String!
): Cursor!
Deprecated: Use CursorLoader
instead.
Wrapper around ContentResolver.query(android.net.Uri , String[], String, String[], String)
that gives the resulting Cursor
to call startManagingCursor
so that the activity will manage its lifecycle for you. If you are targeting android.os.Build.VERSION_CODES#HONEYCOMB
or later, consider instead using LoaderManager
instead, available via getLoaderManager()
.
Warning: Do not call android.database.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
on a cursor from a managed query, the system will not automatically close the cursor and, in that case, you must call android.database.Cursor#close().
Parameters | |
---|---|
uri |
Uri!: The URI of the content provider to query. |
projection |
Array<String!>!: List of columns to return. |
selection |
String!: SQL WHERE clause. |
selectionArgs |
Array<String!>!: The arguments to selection, if any ?s are pesent |
sortOrder |
String!: SQL ORDER BY clause. |
Return | |
---|---|
Cursor! |
The Cursor that was returned by query(). |
moveTaskToBack
open fun moveTaskToBack(nonRoot: Boolean): Boolean
Move the task containing this activity to the back of the activity stack. The activity's order within the task is unchanged.
Parameters | |
---|---|
nonRoot |
Boolean: 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. |
Return | |
---|---|
Boolean |
If the task was moved (or it was already at the back) true is returned, else false. |
navigateUpTo
open fun navigateUpTo(: Intent!): Boolean
Navigate from this activity to the activity specified by upIntent, finishing this activity in the process. If the activity indicated by upIntent already exists in the task's history, this activity and all others before the indicated activity in the history stack will be finished.
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(android.content.Intent)
.
Parameters | |
---|---|
upIntent |
Intent!: An intent representing the target destination for up navigation |
Return | |
---|---|
Boolean |
true if up navigation successfully reached the activity indicated by upIntent and upIntent was delivered to it. false if an instance of the indicated activity could not be found and this activity was simply finished normally. |
navigateUpToFromChild
open funnavigateUpToFromChild(
: Activity!,
: Intent!
): Boolean
Deprecated: Use navigateUpTo(android.content.Intent)
instead.
This is called when a child activity of this one calls its navigateUpTo
method. The default implementation simply calls navigateUpTo(upIntent) on this activity (the parent).
Parameters | |
---|---|
child |
Activity!: The activity making the call. |
upIntent |
Intent!: An intent representing the target destination for up navigation |
Return | |
---|---|
Boolean |
true if up navigation successfully reached the activity indicated by upIntent and upIntent was delivered to it. false if an instance of the indicated activity could not be found and this activity was simply finished normally. |
onActionModeFinished
open fun onActionModeFinished(mode: ActionMode!): Unit
Notifies the activity that an action mode has finished. Activity subclasses overriding this method should call the superclass implementation.
If you override this method you must call through to the superclass implementation.
Parameters | |
---|---|
mode |
ActionMode!: The action mode that just finished. |
onActionModeStarted
open fun onActionModeStarted(mode: ActionMode!): Unit
Notifies the Activity that an action mode has been started. Activity subclasses overriding this method should call the superclass implementation.
If you override this method you must call through to the superclass implementation.
Parameters | |
---|---|
mode |
ActionMode!: The new action mode. |
onActivityReenter
open fun onActivityReenter(
resultCode: Int,
data: Intent!
): Unit
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. This method will only be called if the activity set a result code other than 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.
Parameters | |
---|---|
resultCode |
Int: The integer result code returned by the child activity through its setResult(). |
data |
Intent!: An Intent, which can return result data to the caller (various data can be attached to Intent "extras"). |
onActivityResult
open fun onActivityResult(
requestCode: Int,
resultCode: Int,
data: Intent?,
caller: ComponentCaller
): Unit
Same as onActivityResult(int,int,android.content.Intent)
, but with an extra parameter for the ComponentCaller instance associated with the app that sent the result.
If you want to retrieve the caller without overriding this method, call getCurrentCaller
inside your existing onActivityResult(int,int,android.content.Intent)
.
Note that you should only override one #onActivityResult method.
Parameters | |
---|---|
requestCode |
Int: The integer request code originally supplied to startActivityForResult(), allowing you to identify who this result came from. |
resultCode |
Int: The integer result code returned by the child activity through its setResult(). |
data |
Intent?: An Intent, which can return result data to the caller (various data can be attached to Intent "extras"). This value may be null . |
caller |
ComponentCaller: The ComponentCaller instance associated with the app that sent the intent. This value cannot be null . |
onAttachFragment
open funonAttachFragment(fragment: Fragment!): Unit
Deprecated: Use androidx.fragment.app.FragmentActivity#onAttachFragment(androidx.fragment.app.Fragment)
Called when a Fragment is being attached to this activity, immediately after the call to its android.app.Fragment#onAttach method and before Fragment.onCreate()
.
onAttachedToWindow
open fun onAttachedToWindow(): Unit
Called when the main window associated with the activity has been attached to the window manager. See View.onAttachedToWindow()
for more information.
See Also
onBackPressed
open funonBackPressed(): Unit
Deprecated: Use Starting from Android 13 (API level 33), back event handling is moving to an ahead-of-time model and OnBackInvokedCallback
or androidx.activity.OnBackPressedCallback
to handle back navigation instead.
Activity.onBackPressed()
and KeyEvent.KEYCODE_BACK
should not be used to handle back events (back gesture or back button click). Instead, an OnBackInvokedCallback
should be registered using Activity.getOnBackInvokedDispatcher()
.registerOnBackInvokedCallback(priority, callback)
.
Called when the activity has detected the user's press of the back key. The default implementation depends on the platform version:
- On platform versions prior to
android.os.Build.VERSION_CODES#S
, it finishes the current activity, but you can override this to do whatever you want. - Starting with platform version
android.os.Build.VERSION_CODES#S
, for activities that are the root activity of the task and also declare anandroid.content.IntentFilter
withIntent.ACTION_MAIN
andIntent.CATEGORY_LAUNCHER
in the manifest, the current activity and its task will be moved to the back of the activity stack instead of being finished. Other activities will simply be finished. - If you target version
android.os.Build.VERSION_CODES#S
and override this method, we strongly recommend to call through to the superclass implementation after you finish handling navigation within the app. -
If you target version
android.os.Build.VERSION_CODES#TIRAMISU
or later, you should not use this method but register anOnBackInvokedCallback
on anOnBackInvokedDispatcher
that you can retrieve usinggetOnBackInvokedDispatcher()
. You should also setandroid:enableOnBackInvokedCallback="true"
in the application manifest.Alternatively, you can use
androidx.activity.ComponentActivity#getOnBackPressedDispatcher()
for backward compatibility.
See Also
onConfigurationChanged
open fun onConfigurationChanged(newConfig: Configuration): Unit
Called by the system when the device configuration changes while your activity is running. Note that this will only be called if you have selected configurations you would like to handle with the 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). The only exception is if a size-based configuration is not large enough to be considered significant, in which case the system will not recreate the activity and will instead call this method. For details on this see the documentation on size-based config change.
At the time that this function has been called, your Resources object will have been updated to return resource values matching the new configuration.
Parameters | |
---|---|
newConfig |
Configuration: The new device configuration. This value cannot be null . |
onContextItemSelected
open fun onContextItemSelected(item: MenuItem): Boolean
This hook is called whenever an item in a context menu is selected. The default implementation simply returns false to have the normal processing happen (calling the item's Runnable or sending a message to its Handler as appropriate). You can use this method for any items for which you would like to do processing without those other facilities.
Use 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.
Parameters | |
---|---|
item |
MenuItem: The context menu item that was selected. This value cannot be null . |
Return | |
---|---|
Boolean |
boolean Return false to allow normal context menu processing to proceed, true to consume it here. |
onContextMenuClosed
open fun onContextMenuClosed(: Menu): Unit
This hook is called whenever the context menu is being closed (either by the user canceling the menu with the back/menu button, or when an item is selected).
Parameters | |
---|---|
menu |
Menu: The context menu that is being closed. This value cannot be null . |
onCreate
open fun onCreate(
savedInstanceState: Bundle?,
persistentState: PersistableBundle?
): Unit
Same as onCreate(android.os.Bundle)
but called for those activities created with the attribute android.R.attr#persistableMode
set to persistAcrossReboots
.
Parameters | |
---|---|
savedInstanceState |
Bundle?: if the activity is being re-initialized after previously being shut down then this Bundle contains the data it most recently supplied in #onSaveInstanceState. Note: Otherwise it is null. |
persistentState |
PersistableBundle?: 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. Note: Otherwise it is null. |
See Also
onCreateContextMenu
open fun onCreateContextMenu(
: ContextMenu!,
v: View!,
: ContextMenu.ContextMenuInfo!
): Unit
Called when a context menu for the view
is about to be shown. Unlike onCreateOptionsMenu(android.view.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.
Parameters | |
---|---|
menu |
ContextMenu!: The context menu that is being built |
v |
View!: The view for which the context menu is being built |
menuInfo |
ContextMenu.ContextMenuInfo!: Extra information about the item for which the context menu should be shown. This information will vary depending on the class of v. |
onCreateDescription
open fun onCreateDescription(): CharSequence?
Generate a new description for this activity. This method is called before stopping the activity and can, if desired, return some textual description of its current state to be displayed to the user.
The default implementation returns null, which will cause you to inherit the description from the previous activity. If all activities return null, generally the label of the top activity will be used as the description.
Return | |
---|---|
CharSequence? |
A description of what the user is doing. It should be short and sweet (only a few words). |
See Also
onCreateNavigateUpTaskStack
open fun onCreateNavigateUpTaskStack(: TaskStackBuilder!): Unit
Define the synthetic task stack that will be generated during Up navigation from a different task.
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(android.content.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(android.app.TaskStackBuilder)
.
Parameters | |
---|---|
builder |
TaskStackBuilder!: An empty TaskStackBuilder - the application should add intents representing the desired task stack |
onCreateOptionsMenu
open fun onCreateOptionsMenu(: Menu!): Boolean
Initialize the contents of the Activity's standard options menu. You should place your menu items in to menu.
This is only called once, the first time the options menu is displayed. To update the menu every time it is displayed, see onPrepareOptionsMenu
.
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
method to handle them there.
Parameters | |
---|---|
menu |
Menu!: The options menu in which you place your items. |
Return | |
---|---|
Boolean |
You must return true for the menu to be displayed; if you return false it will not be shown. |
onCreatePanelMenu
open fun onCreatePanelMenu(
featureId: Int,
: Menu
): Boolean
Default implementation of android.view.Window.Callback#onCreatePanelMenu
for activities. This calls through to the new onCreateOptionsMenu
method for the android.view.Window#FEATURE_OPTIONS_PANEL
panel, so that subclasses of Activity don't need to deal with feature codes.
Parameters | |
---|---|
featureId |
Int: The panel being created. |
menu |
Menu: This value cannot be null . |
Return | |
---|---|
Boolean |
boolean You must return true for the panel to be displayed; if you return false it will not be shown. |
onCreatePanelView
open fun onCreatePanelView(featureId: Int): View?
Default implementation of android.view.Window.Callback#onCreatePanelView
for activities. This simply returns null so that all panel sub-windows will have the default menu behavior.
Parameters | |
---|---|
featureId |
Int: Which panel is being created. |
Return | |
---|---|
View? |
view The top-level view to place in the panel. |
onCreateThumbnail
open funonCreateThumbnail(
outBitmap: Bitmap!,
canvas: Canvas!
): Boolean
Deprecated: Method doesn't do anything and will be removed in the future.
onCreateView
open fun onCreateView(
parent: View?,
name: String,
context: Context,
attrs: AttributeSet
): View?
Standard implementation of android.view.LayoutInflater.Factory2#onCreateView(View, String, Context, AttributeSet)
used when inflating with the LayoutInflater returned by #getSystemService. This implementation handles tags to embed fragments inside of the activity.
Parameters | |
---|---|
parent |
View?: This value may be null . |
name |
String: This value cannot be null . |
context |
Context: This value cannot be null . |
attrs |
AttributeSet: This value cannot be null . |
Return | |
---|---|
View? |
This value may be null . |
onCreateView
open fun onCreateView(
name: String,
context: Context,
attrs: AttributeSet
): View?
Standard implementation of android.view.LayoutInflater.Factory#onCreateView
used when inflating with the LayoutInflater returned by #getSystemService. This implementation does nothing and is for pre-android.os.Build.VERSION_CODES#HONEYCOMB
apps. Newer apps should use onCreateView(android.view.View,java.lang.String,android.content.Context,android.util.AttributeSet)
.
Parameters | |
---|---|
name |
String: This value cannot be null . |
context |
Context: This value cannot be null . |
attrs |
AttributeSet: This value cannot be null . |
Return | |
---|---|
View? |
This value may be null . |
onDetachedFromWindow
open fun onDetachedFromWindow(): Unit
Called when the main window associated with the activity has been detached from the window manager. See View.onDetachedFromWindow()
for more information.
onEnterAnimationComplete
open fun onEnterAnimationComplete(): Unit
Activities cannot draw during the period that their windows are animating in. In order to know when it is safe to begin drawing they can override this method which will be called when the entering animation has completed.
onGenericMotionEvent
open fun onGenericMotionEvent(event: MotionEvent!): Boolean
Called when a generic motion event was not handled by any of the views inside of the activity.
Generic motion events describe joystick movements, hover events from mouse or stylus devices, trackpad touches, scroll wheel movements and other motion events not handled by onTouchEvent(android.view.MotionEvent)
or onTrackballEvent(android.view.MotionEvent)
. 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.
Generic motion events with source class android.view.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.
Parameters | |
---|---|
event |
MotionEvent!: The generic motion event being processed. |
Return | |
---|---|
Boolean |
Return true if you have consumed the event, false if you haven't. The default implementation always returns false. |
onGetDirectActions
open fun onGetDirectActions(
cancellationSignal: CancellationSignal,
callback: Consumer<MutableList<DirectAction!>!>
): Unit
Returns the list of direct actions supported by the app.
You should return the list of actions that could be executed in the current context, which is in the current state of the app. If the actions that could be executed by the app changes you should report that via calling VoiceInteractor.notifyDirectActionsChanged()
.
To get the voice interactor you need to call getVoiceInteractor()
which would return non null
only if there is an ongoing voice interaction session. You can also detect when the voice interactor is no longer valid because the voice interaction session that is backing is finished by calling VoiceInteractor.registerOnDestroyedCallback(Executor, Runnable)
.
This method will be called only after onStart()
and before onStop()
.
You should pass to the callback the currently supported direct actions which cannot be null
or contain null
elements.
You should return the action list as soon as possible to ensure the consumer, for example the assistant, is as responsive as possible which would improve user experience of your app.
Parameters | |
---|---|
cancellationSignal |
CancellationSignal: A signal to cancel the operation in progress. This value cannot be null . |
callback |
Consumer<MutableList<DirectAction!>!>: The callback to send the action list. The actions list cannot contain null elements. You can call this on any thread. |
onKeyDown
open fun onKeyDown(
keyCode: Int,
event: KeyEvent!
): Boolean
Called when a key was pressed down and not handled by any of the views inside of the activity. So, for example, key presses while the cursor is inside a TextView will not trigger the event (unless it is a navigation to another object) because TextView handles its own key presses.
If the focused view didn't want this event, this method is called.
The default implementation takes care of KeyEvent.KEYCODE_BACK
by calling onBackPressed()
, though the behavior varies based on the application compatibility mode: for android.os.Build.VERSION_CODES#ECLAIR
or later applications, it will set up the dispatch to call onKeyUp
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. This implementation will also take care of KeyEvent.KEYCODE_ESCAPE
by finishing the activity if it would be closed by touching outside of it.
Other additional default key handling may be performed if configured with setDefaultKeyMode
.
Parameters | |
---|---|
keyCode |
Int: The value in event.getKeyCode(). |
event |
KeyEvent!: Description of the key event. |
Return | |
---|---|
Boolean |
Return true to prevent this event from being propagated further, or false to indicate that you have not handled this event and it should continue to be propagated. |
See Also
onKeyLongPress
open fun onKeyLongPress(
keyCode: Int,
event: KeyEvent!
): Boolean
Default implementation of KeyEvent.Callback.onKeyLongPress()
: always returns false (doesn't handle the event). To receive this callback, you must return true from onKeyDown for the current event stream.
Parameters | |
---|---|
keyCode |
Int: The value in event.getKeyCode(). |
event |
KeyEvent!: Description of the key event. |
Return | |
---|---|
Boolean |
If you handled the event, return true. If you want to allow the event to be handled by the next receiver, return false. |
onKeyMultiple
open fun onKeyMultiple(
keyCode: Int,
repeatCount: Int,
event: KeyEvent!
): Boolean
Default implementation of KeyEvent.Callback.onKeyMultiple()
: always returns false (doesn't handle the event).
Parameters | |
---|---|
keyCode |
Int: The value in event.getKeyCode(). |
count |
Number of pairs as returned by event.getRepeatCount(). |
event |
KeyEvent!: Description of the key event. |
Return | |
---|---|
Boolean |
If you handled the event, return true. If you want to allow the event to be handled by the next receiver, return false. |
onKeyShortcut
open fun onKeyShortcut(
keyCode: Int,
event: KeyEvent!
): Boolean
Called when a key shortcut event is not handled by any of the views in the Activity. Override this method to implement global key shortcuts for the Activity. Key shortcuts can also be implemented by setting the shortcut
property of menu items.
Parameters | |
---|---|
keyCode |
Int: The value in event.getKeyCode(). |
event |
KeyEvent!: Description of the key event. |
Return | |
---|---|
Boolean |
True if the key shortcut was handled. |
onKeyUp
open fun onKeyUp(
keyCode: Int,
event: KeyEvent!
): Boolean
Called when a key was released and not handled by any of the views inside of the activity. So, for example, key presses while the cursor is inside a TextView will not trigger the event (unless it is a navigation to another object) because TextView handles its own key presses.
The default implementation handles KEYCODE_BACK to stop the activity and go back.
Parameters | |
---|---|
keyCode |
Int: The value in event.getKeyCode(). |
event |
KeyEvent!: Description of the key event. |
Return | |
---|---|
Boolean |
Return true to prevent this event from being propagated further, or false to indicate that you have not handled this event and it should continue to be propagated. |
See Also
onLocalVoiceInteractionStarted
open fun onLocalVoiceInteractionStarted(): Unit
Callback to indicate that startLocalVoiceInteraction(android.os.Bundle)
has resulted in a voice interaction session being started. You can now retrieve a voice interactor using getVoiceInteractor()
.
onLocalVoiceInteractionStopped
open fun onLocalVoiceInteractionStopped(): Unit
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. The previously acquired VoiceInteractor
is no longer valid after this.
onMenuItemSelected
open fun onMenuItemSelected(
featureId: Int,
item: MenuItem
): Boolean
Default implementation of android.view.Window.Callback#onMenuItemSelected
for activities. This calls through to the new onOptionsItemSelected
method for the android.view.Window#FEATURE_OPTIONS_PANEL
panel, so that subclasses of Activity don't need to deal with feature codes.
Parameters | |
---|---|
featureId |
Int: The panel that the menu is in. |
item |
MenuItem: This value cannot be null . |
Return | |
---|---|
Boolean |
boolean Return true to finish processing of selection, or false to perform the normal menu handling (calling its Runnable or sending a Message to its target Handler). |
onMenuOpened
open fun onMenuOpened(
featureId: Int,
: Menu
): Boolean
Called when a panel's menu is opened by the user. This may also be called when the menu is changing from one type to another (for example, from the icon menu to the expanded menu).
Parameters | |
---|---|
featureId |
Int: The panel that the menu is in. |
menu |
Menu: This value cannot be null . |
Return | |
---|---|
Boolean |
The default implementation returns true. |
onMultiWindowModeChanged
open funonMultiWindowModeChanged(isInMultiWindowMode: Boolean): Unit
Deprecated: Use onMultiWindowModeChanged(boolean,android.content.res.Configuration)
instead.
Called by the system when the activity changes from fullscreen mode to multi-window mode and visa-versa.
Parameters | |
---|---|
isInMultiWindowMode |
Boolean: True if the activity is in multi-window mode. |
See Also
onMultiWindowModeChanged
open fun onMultiWindowModeChanged(
isInMultiWindowMode: Boolean,
newConfig: Configuration!
): Unit
Called by the system when the activity changes from fullscreen mode to multi-window mode and visa-versa. This method provides the same configuration that will be sent in the following onConfigurationChanged(android.content.res.Configuration)
call after the activity enters this mode.
Parameters | |
---|---|
isInMultiWindowMode |
Boolean: True if the activity is in multi-window mode. |
newConfig |
Configuration!: The new configuration of the activity with the state {@param isInMultiWindowMode}. |
See Also
onNavigateUp
open fun onNavigateUp(): Boolean
This method is called whenever the user chooses to navigate Up within your application's activity hierarchy from the action bar.
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(android.app.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(android.content.Intent)
, and navigateUpTo(android.content.Intent)
for help implementing custom Up navigation. The AppNavigation sample application in the Android SDK is also available for reference.
Return | |
---|---|
Boolean |
true if Up navigation completed successfully and this Activity was finished, false otherwise. |
onNavigateUpFromChild
open funonNavigateUpFromChild(: Activity!): Boolean
Deprecated: Use onNavigateUp()
instead.
This is called when a child activity of this one attempts to navigate up. The default implementation simply calls onNavigateUp() on this activity (the parent).
Parameters | |
---|---|
child |
Activity!: The activity making the call. |
onNewIntent
open fun onNewIntent(
intent: Intent,
caller: ComponentCaller
): Unit
Same as onNewIntent(android.content.Intent)
, but with an extra parameter for the ComponentCaller instance associated with the app that sent the intent.
If you want to retrieve the caller without overriding this method, call getCurrentCaller
inside your existing onNewIntent(android.content.Intent)
.
Note that you should only override one #onNewIntent method.
Parameters | |
---|---|
intent |
Intent: The new intent that was used to start the activity This value cannot be null . |
caller |
ComponentCaller: The ComponentCaller instance associated with the app that sent the intent This value cannot be null . |
onOptionsItemSelected
open fun onOptionsItemSelected(item: MenuItem): Boolean
This hook is called whenever an item in your options menu is selected. The default implementation simply returns false to have the normal processing happen (calling the item's Runnable or sending a message to its Handler as appropriate). You can use this method for any items for which you would like to do processing without those other facilities.
Derived classes should call through to the base class for it to perform the default menu handling.
Parameters | |
---|---|
item |
MenuItem: The menu item that was selected. This value cannot be null . |
Return | |
---|---|
Boolean |
boolean Return false to allow normal menu processing to proceed, true to consume it here. |
See Also
onOptionsMenuClosed
open fun onOptionsMenuClosed(: Menu!): Unit
This hook is called whenever the options menu is being closed (either by the user canceling the menu with the back/menu button, or when an item is selected).
Parameters | |
---|---|
menu |
Menu!: The options menu as last shown or first initialized by onCreateOptionsMenu(). |
onPanelClosed
open fun onPanelClosed(
featureId: Int,
: Menu
): Unit
Default implementation of android.view.Window.Callback#onPanelClosed(int, Menu)
for activities. This calls through to onOptionsMenuClosed(android.view.Menu)
method for the android.view.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(android.view.Menu)
will be called.
Parameters | |
---|---|
featureId |
Int: The panel that is being displayed. |
menu |
Menu: This value cannot be null . |
onPerformDirectAction
open fun onPerformDirectAction(
actionId: String,
arguments: Bundle,
cancellationSignal: CancellationSignal,
resultListener: Consumer<Bundle!>
): Unit
This is called to perform an action previously defined by the app. Apps also have access to getVoiceInteractor()
to follow up on the action.
Parameters | |
---|---|
actionId |
String: The ID for the action you previously reported via onGetDirectActions(android.os.CancellationSignal,java.util.function.Consumer) . This value cannot be null . |
arguments |
Bundle: Any additional arguments provided by the caller that are specific to the given action. This value cannot be null . |
cancellationSignal |
CancellationSignal: A signal to cancel the operation in progress. This value cannot be null . |
resultListener |
Consumer<Bundle!>: The callback to provide the result back to the caller. You can call this on any thread. The result bundle is action specific. This value cannot be null . |
onPictureInPictureModeChanged
open funonPictureInPictureModeChanged(isInPictureInPictureMode: Boolean): Unit
Deprecated: Use onPictureInPictureModeChanged(boolean,android.content.res.Configuration)
instead.
Called by the system when the activity changes to and from picture-in-picture mode.
Parameters | |
---|---|
isInPictureInPictureMode |
Boolean: True if the activity is in picture-in-picture mode. |
onPictureInPictureModeChanged
open fun onPictureInPictureModeChanged(
isInPictureInPictureMode: Boolean,
newConfig: Configuration!
): Unit
Called by the system when the activity changes to and from picture-in-picture mode. This method provides the same configuration that will be sent in the following onConfigurationChanged(android.content.res.Configuration)
call after the activity enters this mode.
Parameters | |
---|---|
isInPictureInPictureMode |
Boolean: True if the activity is in picture-in-picture mode. |
newConfig |
Configuration!: The new configuration of the activity with the state {@param isInPictureInPictureMode}. |
onPictureInPictureRequested
open fun onPictureInPictureRequested(): Boolean
This method is called by the system in various cases where picture in picture mode should be entered if supported.
It is up to the app developer to choose whether to call enterPictureInPictureMode(android.app.PictureInPictureParams)
at this time. For example, the system will call this method when the activity is being put into the background, so the app developer might want to switch an activity into PIP mode instead.
Return | |
---|---|
Boolean |
true if the activity received this callback regardless of if it acts on it or not. If false , the framework will assume the app hasn't been updated to leverage this callback and will in turn send a legacy callback of onUserLeaveHint() for the app to enter picture-in-picture mode. |
onPictureInPictureUiStateChanged
open fun onPictureInPictureUiStateChanged(pipState: PictureInPictureUiState): Unit
Called by the system when the activity is in PiP and has state changes. Compare to onPictureInPictureModeChanged(boolean,android.content.res.Configuration)
, which is only called when PiP mode changes (meaning, enters or exits PiP), this can be called at any time while the activity is in PiP mode. Therefore, all invocation can only happen after onPictureInPictureModeChanged(boolean,android.content.res.Configuration)
is called with true, and before onPictureInPictureModeChanged(boolean,android.content.res.Configuration)
is called with false. You would not need to worry about cases where this is called and the activity is not in Picture-In-Picture mode. For managing cases where the activity enters/exits Picture-in-Picture (e.g. resources clean-up on exit), use onPictureInPictureModeChanged(boolean,android.content.res.Configuration)
. The default state is everything declared in PictureInPictureUiState
is false, such as PictureInPictureUiState.isStashed()
.
Parameters | |
---|---|
pipState |
PictureInPictureUiState: the new Picture-in-Picture state. This value cannot be null . |
onPostCreate
open fun onPostCreate(
savedInstanceState: Bundle?,
persistentState: PersistableBundle?
): Unit
This is the same as onPostCreate(android.os.Bundle)
but is called for activities created with the attribute android.R.attr#persistableMode
set to persistAcrossReboots
.
Parameters | |
---|---|
savedInstanceState |
Bundle?: The data most recently supplied in #onSaveInstanceState This value may be null . |
persistentState |
PersistableBundle?: The data coming from the PersistableBundle first saved in onSaveInstanceState(android.os.Bundle,android.os.PersistableBundle) . This value may be null . |
See Also
onPrepareNavigateUpTaskStack
open fun onPrepareNavigateUpTaskStack(: TaskStackBuilder!): Unit
Prepare the synthetic task stack that will be generated during Up navigation from a different task.
This method receives the TaskStackBuilder
with the constructed series of Intents as generated by onCreateNavigateUpTaskStack(android.app.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.
Parameters | |
---|---|
builder |
TaskStackBuilder!: A TaskStackBuilder that has been populated with Intents by onCreateNavigateUpTaskStack. |
onPrepareOptionsMenu
open fun onPrepareOptionsMenu(: Menu!): Boolean
Prepare the Screen's standard options menu to be displayed. This is called right before the menu is shown, every time it is shown. You can use this method to efficiently enable/disable items or otherwise dynamically modify the contents.
The default implementation updates the system menu items based on the activity's state. Deriving classes should always call through to the base class implementation.
Parameters | |
---|---|
menu |
Menu!: The options menu as last shown or first initialized by onCreateOptionsMenu(). |
Return | |
---|---|
Boolean |
You must return true for the menu to be displayed; if you return false it will not be shown. |
See Also
onPreparePanel
open fun onPreparePanel(
featureId: Int,
view: View?,
: Menu
): Boolean
Default implementation of android.view.Window.Callback#onPreparePanel
for activities. This calls through to the new onPrepareOptionsMenu
method for the android.view.Window#FEATURE_OPTIONS_PANEL
panel, so that subclasses of Activity don't need to deal with feature codes.
Parameters | |
---|---|
featureId |
Int: The panel that is being displayed. |
view |
View?: This value may be null . |
menu |
Menu: This value cannot be null . |
Return | |
---|---|
Boolean |
boolean You must return true for the panel to be displayed; if you return false it will not be shown. |
onProvideAssistContent
open fun onProvideAssistContent(outContent: AssistContent!): Unit
This is called when the user is requesting an assist, to provide references to content related to the current activity. Before being called, the 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.
Parameters | |
---|---|
outContent |
AssistContent!: The assist content to return. |
onProvideAssistData
open fun onProvideAssistData(data: Bundle!): Unit
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. 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
.
onProvideKeyboardShortcuts
open fun onProvideKeyboardShortcuts(
data: MutableList<KeyboardShortcutGroup!>!,
: Menu?,
deviceId: Int
): Unit
Parameters | |
---|---|
data |
MutableList<KeyboardShortcutGroup!>!: The data list to populate with shortcuts. |
menu |
Menu?: The current menu, which may be null. |
deviceId |
Int: The id for the connected device the shortcuts should be provided for. |
onProvideReferrer
open fun onProvideReferrer(): Uri!
Override to generate the desired referrer for the content currently being shown by the app. The default implementation returns null, meaning the referrer will simply be the android-app: of the package name of this activity. Return a non-null Uri to have that supplied as the Intent.EXTRA_REFERRER
of any activities started from it.
onRequestPermissionsResult
open fun onRequestPermissionsResult(
requestCode: Int,
permissions: Array<String!>,
grantResults: IntArray
): Unit
Callback for the result from requesting permissions. This method is invoked for every call on #requestPermissions
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.
Parameters | |
---|---|
requestCode |
Int: The request code passed in #requestPermissions. |
permissions |
Array<String!>: The requested permissions. Never null. |
grantResults |
IntArray: The grant results for the corresponding permissions which is either android.content.pm.PackageManager#PERMISSION_GRANTED or android.content.pm.PackageManager#PERMISSION_DENIED . Never null. |
See Also
onRequestPermissionsResult
open fun onRequestPermissionsResult(
requestCode: Int,
permissions: Array<String!>,
grantResults: IntArray,
deviceId: Int
): Unit
Callback for the result from requesting permissions. This method is invoked for every call on #requestPermissions.
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.
Parameters | |
---|---|
requestCode |
Int: The request code passed in #requestPermissions. |
permissions |
Array<String!>: The requested permissions. Never null. |
grantResults |
IntArray: The grant results for the corresponding permissions which is either android.content.pm.PackageManager#PERMISSION_GRANTED or android.content.pm.PackageManager#PERMISSION_DENIED . Never null. |
deviceId |
Int: The deviceId for which permissions were requested. The primary/physical device is assigned Context.DEVICE_ID_DEFAULT , and virtual devices are assigned unique device Ids. |
See Also
onRestoreInstanceState
open fun onRestoreInstanceState(
savedInstanceState: Bundle?,
persistentState: PersistableBundle?
): Unit
This is the same as onRestoreInstanceState(android.os.Bundle)
but is called for activities created with the attribute android.R.attr#persistableMode
set to persistAcrossReboots
. The android.os.PersistableBundle
passed came from the restored PersistableBundle first saved in onSaveInstanceState(android.os.Bundle,android.os.PersistableBundle)
.
This method is called between onStart
and #onPostCreate.
If this method is called onRestoreInstanceState(android.os.Bundle)
will not be called.
At least one of savedInstanceState
or persistentState
will not be null.
Parameters | |
---|---|
savedInstanceState |
Bundle?: the data most recently supplied in #onSaveInstanceState or null. |
persistentState |
PersistableBundle?: the data most recently supplied in #onSaveInstanceState or null. |
See Also
onRetainNonConfigurationInstance
open fun onRetainNonConfigurationInstance(): Any!
Called by the system, as part of destroying an activity due to a configuration change, when it is known that a new instance will immediately be created for the new configuration. You can return any object you like here, including the activity instance itself, which can later be retrieved by calling getLastNonConfigurationInstance()
in the new activity instance. If you are targeting android.os.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:
- The function will be called between
onStop
andonDestroy
. - A new instance of the activity will always be immediately created after this one's
onDestroy()
is called. In particular, no messages will be dispatched during this time (when the returned object does not have an activity to be associated with). - The object you return here will always be available from the
getLastNonConfigurationInstance()
method of the following activity instance as described there.
These guarantees are designed so that an activity can use this API to propagate extensive state from the old to new activity instance, from loaded bitmaps, to network connections, to evenly actively running threads. Note that you should not propagate any data that may change based on the configuration, including any data loaded from resources such as strings, layouts, or drawables.
The guarantee of no message handling during the switch to the next activity simplifies use with active objects. For example if your retained state is an android.os.AsyncTask
you are guaranteed that its call back functions (like android.os.AsyncTask#onPostExecute
) will not be called from the call here until you execute the next instance's onCreate(android.os.Bundle)
. (Note however that there is of course no such guarantee for android.os.AsyncTask#doInBackground
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.
Return | |
---|---|
Any! |
any Object holding the desired state to propagate to the next activity instance |
onSaveInstanceState
open fun onSaveInstanceState(
outState: Bundle,
outPersistentState: PersistableBundle
): Unit
This is the same as #onSaveInstanceState but is called for activities created with the attribute android.R.attr#persistableMode
set to persistAcrossReboots
. The android.os.PersistableBundle
passed in will be saved and presented in onCreate(android.os.Bundle,android.os.PersistableBundle)
the first time that this activity is restarted following the next device reboot.
Parameters | |
---|---|
outState |
Bundle: Bundle in which to place your saved state. This value cannot be null . |
outPersistentState |
PersistableBundle: State which will be saved across reboots. This value cannot be null . |
onSearchRequested
open fun onSearchRequested(): Boolean
Return | |
---|---|
Boolean |
true if search launched, false if activity refuses (blocks) |
See Also
onSearchRequested
open fun onSearchRequested(searchEvent: SearchEvent?): Boolean
This hook is called when the user signals the desire to start a search.
You can use this function as a simple way to launch the search UI, in response to a menu item, search button, or other widgets within your activity. Unless overridden, 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
or Configuration.UI_MODE_TYPE_WATCH
, the default implementation changes to simply return false and you must supply your own custom implementation if you want to support search.
Parameters | |
---|---|
searchEvent |
SearchEvent?: The SearchEvent that signaled this search. This value may be null . |
Return | |
---|---|
Boolean |
Returns 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. |
See Also
onStateNotSaved
open funonStateNotSaved(): Unit
Deprecated: starting with android.os.Build.VERSION_CODES#P
onSaveInstanceState is called after onStop
, so this hint isn't accurate anymore: you should consider your state not saved in between onStart
and onStop
callbacks inclusively.
Called when an onResume
is coming up, prior to other pre-resume callbacks such as #onNewIntent and #onActivityResult. This is primarily intended to give the activity a hint that its state is no longer saved -- it will generally be called after #onSaveInstanceState and prior to the activity being resumed/started again.
onTopResumedActivityChanged
open fun onTopResumedActivityChanged(isTopResumedActivity: Boolean): Unit
Called when activity gets or loses the top resumed position in the system.
Starting with android.os.Build.VERSION_CODES#Q
multiple activities can be resumed at the same time in multi-window and multi-display modes. This callback should be used instead of onResume()
as an indication that the activity can try to open exclusive-access devices like camera.
It will always be delivered after the activity was resumed and before it is paused. In some cases it might be skipped and activity can go straight from onResume()
to onPause()
without receiving the top resumed state.
Parameters | |
---|---|
isTopResumedActivity |
Boolean: true if it's the topmost resumed activity in the system, false otherwise. A call with this as true will always be followed by another one with false . |
onTouchEvent
open fun onTouchEvent(event: MotionEvent!): Boolean
Called when a touch screen event was not handled by any of the views inside of the activity. This is most useful to process touch events that happen outside of your window bounds, where there is no view to receive it.
Parameters | |
---|---|
event |
MotionEvent!: The touch screen event being processed. |
Return | |
---|---|
Boolean |
Return true if you have consumed the event, false if you haven't. |
onTrackballEvent
open fun onTrackballEvent(event: MotionEvent!): Boolean
Called when the trackball was moved and not handled by any of the views inside of the activity. So, for example, if the trackball moves while focus is on a button, you will receive a call here because buttons do not normally do anything with trackball events. The call here happens before trackball movements are converted to DPAD key events, which then get sent back to the view hierarchy, and will be processed at the point for things like focus navigation.
Parameters | |
---|---|
event |
MotionEvent!: The trackball event being processed. |
Return | |
---|---|
Boolean |
Return true if you have consumed the event, false if you haven't. The default implementation always returns false. |
onTrimMemory
open fun onTrimMemory(level: Int): Unit
Parameters | |
---|---|
level |
Int: The context of the trim, giving a hint of the amount of trimming the application may like to perform. Value is android.content.ComponentCallbacks2#TRIM_MEMORY_COMPLETE , android.content.ComponentCallbacks2#TRIM_MEMORY_MODERATE , android.content.ComponentCallbacks2#TRIM_MEMORY_BACKGROUND , android.content.ComponentCallbacks2#TRIM_MEMORY_UI_HIDDEN , android.content.ComponentCallbacks2#TRIM_MEMORY_RUNNING_CRITICAL , android.content.ComponentCallbacks2#TRIM_MEMORY_RUNNING_LOW , or android.content.ComponentCallbacks2#TRIM_MEMORY_RUNNING_MODERATE |
onUserInteraction
open fun onUserInteraction(): Unit
Called whenever a key, touch, or trackball event is dispatched to the activity. Implement this method if you wish to know that the user has interacted with the device in some way while your activity is running. This callback and onUserLeaveHint
are intended to help activities manage status bar notifications intelligently; specifically, for helping activities determine the proper time to cancel a notification.
All calls to your activity's onUserLeaveHint
callback will be accompanied by calls to onUserInteraction
. This ensures that your activity will be told of relevant user activity such as pulling down the notification pane and touching an item there.
Note that this callback will be invoked for the touch down action that begins a touch gesture, but may not be invoked for the touch-moved and touch-up actions that follow.
See Also
onVisibleBehindCanceled
open funonVisibleBehindCanceled(): Unit
Deprecated: This method's functionality is no longer supported as of android.os.Build.VERSION_CODES#O
and will be removed in a future release.
Called when a translucent activity over this activity is becoming opaque or another activity is being launched. Activities that override this method must call 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.
If you override this method you must call through to the superclass implementation.
See Also
onWindowAttributesChanged
open fun onWindowAttributesChanged(params: WindowManager.LayoutParams!): Unit
onWindowFocusChanged
open fun onWindowFocusChanged(hasFocus: Boolean): Unit
Called when the current Window
of the activity gains or loses focus. This is the best indicator of whether this activity is the entity with which the user actively interacts. 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 lifecycle. 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 foreground 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.
Starting with android.os.Build.VERSION_CODES#Q
there can be multiple resumed activities at the same time in multi-window mode, so resumed state does not guarantee window focus even if there are no overlays above.
If the intent is to know when an activity is the topmost active, the one the user interacted with last among all activities but not including non-activity windows like dialogs and popups, then onTopResumedActivityChanged(boolean)
should be used. On platform versions prior to android.os.Build.VERSION_CODES#Q
, onResume
is the best indicator.
Parameters | |
---|---|
hasFocus |
Boolean: Whether the window of this activity has focus. |
onWindowStartingActionMode
open fun onWindowStartingActionMode(callback: ActionMode.Callback!): ActionMode?
Give the Activity a chance to control the UI for an action mode requested by the system.
Note: If you are looking for a notification callback that an action mode has been started for this activity, see onActionModeStarted(android.view.ActionMode)
.
Parameters | |
---|---|
callback |
ActionMode.Callback!: The callback that should control the new action mode |
Return | |
---|---|
ActionMode? |
The new action mode, or null if the activity does not want to provide special handling for this action mode. (It will be handled by the system.) |
onWindowStartingActionMode
open fun onWindowStartingActionMode(
callback: ActionMode.Callback!,
type: Int
): ActionMode?
Called when an action mode is being started for this window. Gives the callback an opportunity to handle the action mode in its own unique and beautiful way. If this method returns null the system can choose a way to present the mode or choose not to start the mode at all.
Parameters | |
---|---|
callback |
ActionMode.Callback!: Callback to control the lifecycle of this action mode |
type |
Int: One of ActionMode.TYPE_PRIMARY or ActionMode.TYPE_FLOATING . |
Return | |
---|---|
ActionMode? |
This value may be null . |
openContextMenu
open fun openContextMenu(view: View!): Unit
Programmatically opens the context menu for a particular view
. The view
should have been added via registerForContextMenu(android.view.View)
.
Parameters | |
---|---|
view |
View!: The view to show the context menu for. |
openOptionsMenu
open fun openOptionsMenu(): Unit
Programmatically opens the options menu. If the options menu is already open, this method does nothing.
overrideActivityTransition
open fun overrideActivityTransition(
overrideType: Int,
enterAnim: Int,
exitAnim: Int
): Unit
Customizes the animation for the activity transition with this activity. This can be called at any time while the activity still alive.
This is a more robust method of overriding the transition animation at runtime without relying on overridePendingTransition(int,int)
which doesn't work for predictive back. However, the animation set from overridePendingTransition(int,int)
still has higher priority when the system is looking for the next transition animation.
The animations resources set by this method will be chosen if and only if the activity is on top of the task while activity transitions are being played. For example, if we want to customize the opening transition when launching Activity B which gets started from Activity A, we should call this method inside B's onCreate with overrideType = OVERRIDE_TRANSITION_OPEN
because the Activity B will on top of the task. And if we want to customize the closing transition when finishing Activity B and back to Activity A, since B is still is above A, we should call this method in Activity B with overrideType = OVERRIDE_TRANSITION_CLOSE
.
If an Activity has called this method, and it also set another activity animation by Window.setWindowAnimations(int)
, the system will choose the animation set from this method.
Note that Window.setWindowAnimations
, overridePendingTransition(int,int)
and this method will be ignored if the Activity is started with ActivityOptions.makeSceneTransitionAnimation(Activity, Pair[])
. Also note that this method can only be used to customize cross-activity transitions but not cross-task transitions which are fully non-customizable as of Android 11.
Parameters | |
---|---|
overrideType |
Int: OVERRIDE_TRANSITION_OPEN This animation will be used when starting/entering an activity. OVERRIDE_TRANSITION_CLOSE This animation will be used when finishing/closing an activity. Value is android.app.Activity#OVERRIDE_TRANSITION_OPEN , or android.app.Activity#OVERRIDE_TRANSITION_CLOSE |
enterAnim |
Int: A resource ID of the animation resource to use for the incoming activity. Use 0 for no animation. |
exitAnim |
Int: A resource ID of the animation resource to use for the outgoing activity. Use 0 for no animation. |
overrideActivityTransition
open fun overrideActivityTransition(
overrideType: Int,
enterAnim: Int,
exitAnim: Int,
backgroundColor: Int
): Unit
Customizes the animation for the activity transition with this activity. This can be called at any time while the activity still alive.
This is a more robust method of overriding the transition animation at runtime without relying on overridePendingTransition(int,int)
which doesn't work for predictive back. However, the animation set from overridePendingTransition(int,int)
still has higher priority when the system is looking for the next transition animation.
The animations resources set by this method will be chosen if and only if the activity is on top of the task while activity transitions are being played. For example, if we want to customize the opening transition when launching Activity B which gets started from Activity A, we should call this method inside B's onCreate with overrideType = OVERRIDE_TRANSITION_OPEN
because the Activity B will on top of the task. And if we want to customize the closing transition when finishing Activity B and back to Activity A, since B is still is above A, we should call this method in Activity B with overrideType = OVERRIDE_TRANSITION_CLOSE
.
If an Activity has called this method, and it also set another activity animation by Window.setWindowAnimations(int)
, the system will choose the animation set from this method.
Note that Window.setWindowAnimations
, overridePendingTransition(int,int)
and this method will be ignored if the Activity is started with ActivityOptions.makeSceneTransitionAnimation(Activity, Pair[])
. Also note that this method can only be used to customize cross-activity transitions but not cross-task transitions which are fully non-customizable as of Android 11.
Parameters | |
---|---|
overrideType |
Int: OVERRIDE_TRANSITION_OPEN This animation will be used when starting/entering an activity. OVERRIDE_TRANSITION_CLOSE This animation will be used when finishing/closing an activity. Value is android.app.Activity#OVERRIDE_TRANSITION_OPEN , or android.app.Activity#OVERRIDE_TRANSITION_CLOSE |
enterAnim |
Int: A resource ID of the animation resource to use for the incoming activity. Use 0 for no animation. |
exitAnim |
Int: A resource ID of the animation resource to use for the outgoing activity. Use 0 for no animation. |
backgroundColor |
Int: The background color to use for the background during the animation if the animation requires a background. Set to Color.TRANSPARENT to not override the default color. |
overridePendingTransition
open funoverridePendingTransition(
enterAnim: Int,
exitAnim: Int
): Unit
Deprecated: Use overrideActivityTransition(int,int,int)
} instead.
Call immediately after one of the flavors of #startActivity(android.content.Intent) or finish
to specify an explicit transition animation to perform next.
As of android.os.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(android.content.Intent,android.os.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.
Af of android.os.Build.VERSION_CODES#S
application can only specify a transition animation when the transition happens within the same task. System default animation is used for cross-task transition animations.
Parameters | |
---|---|
enterAnim |
Int: A resource ID of the animation resource to use for the incoming activity. Use 0 for no animation. |
exitAnim |
Int: A resource ID of the animation resource to use for the outgoing activity. Use 0 for no animation. |
overridePendingTransition
open funoverridePendingTransition(
enterAnim: Int,
exitAnim: Int,
backgroundColor: Int
): Unit
Deprecated: Use overrideActivityTransition(int,int,int,int)
} instead.
Call immediately after one of the flavors of #startActivity(android.content.Intent) or finish
to specify an explicit transition animation to perform next.
As of android.os.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(android.content.Intent,android.os.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.
Parameters | |
---|---|
enterAnim |
Int: A resource ID of the animation resource to use for the incoming activity. Use 0 for no animation. |
exitAnim |
Int: A resource ID of the animation resource to use for the outgoing activity. Use 0 for no animation. |
backgroundColor |
Int: The background color to use for the background during the animation if the animation requires a background. Set to 0 to not override the default color. |
postponeEnterTransition
open fun postponeEnterTransition(): Unit
Postpone the entering activity transition when Activity was started with android.app.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