Added in API level 1

Instrumentation

open class Instrumentation
kotlin.Any
   ↳ android.app.Instrumentation

Base class for implementing application instrumentation code. When running with instrumentation turned on, this class will be instantiated for you before any of the application code, allowing you to monitor all of the interaction the system has with the application. An Instrumentation implementation is described to the system through an AndroidManifest.xml's <instrumentation> tag.

Summary

Nested classes
open

Information about a particular kind of Intent that is being monitored.

Description of a Activity execution result to return to the original activity.

Constants
static String

If included in the status or final bundle sent to an IInstrumentationWatcher, this key identifies the class that is writing the report.

static String

If included in the status or final bundle sent to an IInstrumentationWatcher, this key identifies a string which can simply be printed to the output stream.

Public constructors

Public methods
open TestLooperManager!

Takes control of the execution of messages on the specified looper until TestLooperManager#release is called.

open Unit

Add a new ActivityMonitor that will be checked whenever an activity is started.

open Instrumentation.ActivityMonitor!

A convenience wrapper for addMonitor(android.app.Instrumentation.ActivityMonitor) that creates an intent filter matching ActivityMonitor for you and returns it.

open Instrumentation.ActivityMonitor!

A convenience wrapper for addMonitor(android.app.Instrumentation.ActivityMonitor) that creates a class matching ActivityMonitor for you and returns it.

open Unit
addResults(results: Bundle!)

Report some results in the middle of instrumentation execution.

open Unit
callActivityOnCreate(activity: Activity!, icicle: Bundle!)

Perform calling of an activity's android.

open Unit
callActivityOnCreate(activity: Activity!, icicle: Bundle!, persistentState: PersistableBundle!)

Perform calling of an activity's android.

open Unit

open Unit
callActivityOnNewIntent(activity: Activity!, intent: Intent!)

Perform calling of an activity's Activity#onNewIntent method.

open Unit

Perform calling of an activity's Activity#onPause method.

open Unit

Perform calling of an activity's Activity#onPictureInPictureRequested method.

open Unit
callActivityOnPostCreate(activity: Activity, savedInstanceState: Bundle?)

Perform calling of an activity's android.

open Unit
callActivityOnPostCreate(activity: Activity, savedInstanceState: Bundle?, persistentState: PersistableBundle?)

Perform calling of an activity's android.

open Unit

Perform calling of an activity's Activity#onRestart method.

open Unit
callActivityOnRestoreInstanceState(activity: Activity, savedInstanceState: Bundle)

Perform calling of an activity's android.

open Unit
callActivityOnRestoreInstanceState(activity: Activity, savedInstanceState: Bundle?, persistentState: PersistableBundle?)

Perform calling of an activity's android.

open Unit

Perform calling of an activity's Activity#onResume method.

open Unit

Perform calling of an activity's android.

open Unit
callActivityOnSaveInstanceState(activity: Activity, outState: Bundle, outPersistentState: PersistableBundle)

Perform calling of an activity's android.

open Unit

Perform calling of an activity's Activity#onStart method.

open Unit

Perform calling of an activity's Activity#onStop method.

open Unit

Perform calling of an activity's Activity#onUserLeaveHint method.

open Unit

Perform calling of the application's Application#onCreate method.

open Boolean

Test whether an existing ActivityMonitor has been hit.

open Unit

open Unit
finish(resultCode: Int, results: Bundle!)

Terminate instrumentation of the application.

open Bundle!

Returns a bundle with the current results from the allocation counting.

open Bundle!

Returns a bundle with the counts for various binder counts for this process.

open ComponentName!

Returns complete component name of this instrumentation.

open Context!

Return the Context of this instrumentation's package.

open String!

Return the name of the process this instrumentation is running in.

open Context!

Return a Context for the target application being instrumented.

open UiAutomation!

Gets the UiAutomation instance with no flags set.

open UiAutomation!

Gets the UiAutomation instance with flags set.

open Boolean
invokeContextMenuAction(targetActivity: Activity!, id: Int, flag: Int)

Show the context menu for the currently focused view and executes a particular context menu item.

open Boolean
invokeMenuActionSync(targetActivity: Activity!, id: Int, flag: Int)

Execute a particular menu item.

open Boolean

Check whether this instrumentation was started with profiling enabled.

open Activity!
newActivity(clazz: Class<*>!, context: Context!, token: IBinder!, application: Application!, intent: Intent!, info: ActivityInfo!, title: CharSequence!, parent: Activity!, id: String!, lastNonConfigurationInstance: Any!)

Perform instantiation of an Activity object.

open Activity!
newActivity(cl: ClassLoader!, className: String!, intent: Intent!)

Perform instantiation of the process's Activity object.

open Application!
newApplication(cl: ClassLoader!, className: String!, context: Context!)

Perform instantiation of the process's Application object.

open static Application!
newApplication(clazz: Class<*>!, context: Context!)

Perform instantiation of the process's Application object.

open Unit
onCreate(arguments: Bundle!)

Called when the instrumentation is starting, before any application code has been loaded.

open Unit

Called when the instrumented application is stopping, after all of the normal application cleanup has occurred.

open Boolean
onException(obj: Any!, e: Throwable!)

This is called whenever the system captures an unhandled exception that was thrown by the application.

open Unit

Method where the instrumentation thread enters execution.

open Unit

Remove an ActivityMonitor that was previously added with #addMonitor.

open Unit

Resets the touch mode to the device default.

open Unit

Execute a call on the application's main thread, blocking until it is complete.

open Unit

Sends up and down key events with the given key code to the currently focused window, and waits for it to be processed.

open Unit

Sends up and down key events with the given key code to the currently focused window, and waits for it to be processed.

open Unit

Sends a key event to the currently focused window, and waits for it to be processed.

open Unit

Dispatches a pointer event into a window owned by the instrumented application, and waits for it to be processed.

open Unit
sendStatus(resultCode: Int, results: Bundle!)

Provide a status report about the application.

open Unit

Sends the key events that result in the given text being typed into the currently focused window, and waits for it to be processed.

open Unit

Dispatches a trackball event into the currently focused window, and waits for it to be processed.

open Unit

open Unit

Force the global system in or out of touch mode.

open Unit

Create and start a new thread in which to run instrumentation.

open Activity!

Start a new activity and wait for it to begin running before returning.

open Activity
startActivitySync(intent: Intent, options: Bundle?)

Start a new activity and wait for it to begin running before returning.

open Unit

open Unit

open Unit

This method will start profiling if isProfiling() returns true.

open Unit

open Unit

Stops profiling if isProfiling() returns true.

open Unit
waitForIdle(recipient: Runnable!)

Schedule a callback for when the application's main thread goes idle (has no more events to process).

open Unit

Synchronously wait for the application to be idle.

open Activity!

Wait for an existing ActivityMonitor to be hit.

open Activity!

Wait for an existing ActivityMonitor to be hit till the timeout expires.

Constants

REPORT_KEY_IDENTIFIER

Added in API level 1
static val REPORT_KEY_IDENTIFIER: String

If included in the status or final bundle sent to an IInstrumentationWatcher, this key identifies the class that is writing the report. This can be used to provide more structured logging or reporting capabilities in the IInstrumentationWatcher.

Value: "id"

REPORT_KEY_STREAMRESULT

Added in API level 1
static val REPORT_KEY_STREAMRESULT: String

If included in the status or final bundle sent to an IInstrumentationWatcher, this key identifies a string which can simply be printed to the output stream. Using these streams provides a "pretty printer" version of the status & final packets. Any bundles including this key should also include the complete set of raw key/value pairs, so that the instrumentation can also be launched, and results collected, by an automated system.

Value: "stream"

Public constructors

Instrumentation

Added in API level 1
Instrumentation()

Public methods

acquireLooperManager

Added in API level 26
open fun acquireLooperManager(looper: Looper!): TestLooperManager!

Takes control of the execution of messages on the specified looper until TestLooperManager#release is called.

addMonitor

Added in API level 1
open fun addMonitor(monitor: Instrumentation.ActivityMonitor!): Unit

Add a new ActivityMonitor that will be checked whenever an activity is started. The monitor is added after any existing ones; the monitor will be hit only if none of the existing monitors can themselves handle the Intent.

Parameters
monitor Instrumentation.ActivityMonitor!: The new ActivityMonitor to see.

addMonitor

Added in API level 1
open fun addMonitor(
    filter: IntentFilter!,
    result: Instrumentation.ActivityResult!,
    block: Boolean
): Instrumentation.ActivityMonitor!

A convenience wrapper for addMonitor(android.app.Instrumentation.ActivityMonitor) that creates an intent filter matching ActivityMonitor for you and returns it.

Parameters
filter IntentFilter!: The set of intents this monitor is responsible for.
result Instrumentation.ActivityResult!: A canned result to return if the monitor is hit; can be null.
block Boolean: Controls whether the monitor should block the activity start (returning its canned result) or let the call proceed.
Return
Instrumentation.ActivityMonitor! The newly created and added activity monitor.

addMonitor

Added in API level 1
open fun addMonitor(
    cls: String!,
    result: Instrumentation.ActivityResult!,
    block: Boolean
): Instrumentation.ActivityMonitor!

A convenience wrapper for addMonitor(android.app.Instrumentation.ActivityMonitor) that creates a class matching ActivityMonitor for you and returns it.

Parameters
cls String!: The activity class this monitor is responsible for.
result Instrumentation.ActivityResult!: A canned result to return if the monitor is hit; can be null.
block Boolean: Controls whether the monitor should block the activity start (returning its canned result) or let the call proceed.
Return
Instrumentation.ActivityMonitor! The newly created and added activity monitor.

addResults

Added in API level 26
open fun addResults(results: Bundle!): Unit

Report some results in the middle of instrumentation execution. Later results (including those provided by finish) will be combined with android.os.Bundle#putAll.

callActivityOnCreate

Added in API level 1
open fun callActivityOnCreate(
    activity: Activity!,
    icicle: Bundle!
): Unit

Perform calling of an activity's android.app.Activity#onCreate method. The default implementation simply calls through to that method.

Parameters
activity Activity!: The activity being created.
icicle Bundle!: The previously frozen state (or null) to pass through to onCreate().

callActivityOnCreate

Added in API level 21
open fun callActivityOnCreate(
    activity: Activity!,
    icicle: Bundle!,
    persistentState: PersistableBundle!
): Unit

Perform calling of an activity's android.app.Activity#onCreate method. The default implementation simply calls through to that method.

Parameters
activity Activity!: The activity being created.
icicle Bundle!: The previously frozen state (or null) to pass through to
persistentState PersistableBundle!: The previously persisted state (or null)

callActivityOnDestroy

Added in API level 1
open fun callActivityOnDestroy(activity: Activity!): Unit

callActivityOnNewIntent

Added in API level 1
open fun callActivityOnNewIntent(
    activity: Activity!,
    intent: Intent!
): Unit

Perform calling of an activity's Activity#onNewIntent method. The default implementation simply calls through to that method.

Parameters
activity Activity!: The activity receiving a new Intent.
intent Intent!: The new intent being received.

callActivityOnPause

Added in API level 1
open fun callActivityOnPause(activity: Activity!): Unit

Perform calling of an activity's Activity#onPause method. The default implementation simply calls through to that method.

Parameters
activity Activity!: The activity being paused.

callActivityOnPictureInPictureRequested

Added in API level 30
open fun callActivityOnPictureInPictureRequested(activity: Activity): Unit

Perform calling of an activity's Activity#onPictureInPictureRequested method. The default implementation simply calls through to that method.

Parameters
activity Activity: The activity being notified that picture-in-picture is being requested. This value cannot be null.

callActivityOnPostCreate

Added in API level 1
open fun callActivityOnPostCreate(
    activity: Activity,
    savedInstanceState: Bundle?
): Unit

Perform calling of an activity's android.app.Activity#onPostCreate method. The default implementation simply calls through to that method.

Parameters
activity Activity: The activity being created. This value cannot be null.
savedInstanceState Bundle?: The previously saved state (or null) to pass through to onPostCreate().

callActivityOnPostCreate

Added in API level 21
open fun callActivityOnPostCreate(
    activity: Activity,
    savedInstanceState: Bundle?,
    persistentState: PersistableBundle?
): Unit

Perform calling of an activity's android.app.Activity#onPostCreate method. The default implementation simply calls through to that method.

Parameters
activity Activity: The activity being created. This value cannot be null.
savedInstanceState Bundle?: The previously frozen state (or null) to pass through to onPostCreate().
persistentState PersistableBundle?: The previously persisted state (or null)

callActivityOnRestart

Added in API level 1
open fun callActivityOnRestart(activity: Activity!): Unit

Perform calling of an activity's Activity#onRestart method. The default implementation simply calls through to that method.

Parameters
activity Activity!: The activity being restarted.

callActivityOnRestoreInstanceState

Added in API level 1
open fun callActivityOnRestoreInstanceState(
    activity: Activity,
    savedInstanceState: Bundle
): Unit

Perform calling of an activity's android.app.Activity#onRestoreInstanceState method. The default implementation simply calls through to that method.

Parameters
activity Activity: The activity being restored. This value cannot be null.
savedInstanceState Bundle: The previously saved state being restored. This value cannot be null.

callActivityOnRestoreInstanceState

Added in API level 21
open fun callActivityOnRestoreInstanceState(
    activity: Activity,
    savedInstanceState: Bundle?,
    persistentState: PersistableBundle?
): Unit

Perform calling of an activity's android.app.Activity#onRestoreInstanceState method. The default implementation simply calls through to that method.

Parameters
activity Activity: The activity being restored. This value cannot be null.
savedInstanceState Bundle?: The previously saved state being restored (or null).
persistentState PersistableBundle?: The previously persisted state (or null)

callActivityOnResume

Added in API level 1
open fun callActivityOnResume(activity: Activity!): Unit

Perform calling of an activity's Activity#onResume method. The default implementation simply calls through to that method.

Parameters
activity Activity!: The activity being resumed.

callActivityOnSaveInstanceState

Added in API level 1
open fun callActivityOnSaveInstanceState(
    activity: Activity,
    outState: Bundle
): Unit

Perform calling of an activity's android.app.Activity#onSaveInstanceState method. The default implementation simply calls through to that method.

Parameters
activity Activity: The activity being saved. This value cannot be null.
outState Bundle: The bundle to pass to the call. This value cannot be null.

callActivityOnSaveInstanceState

Added in API level 21
open fun callActivityOnSaveInstanceState(
    activity: Activity,
    outState: Bundle,
    outPersistentState: PersistableBundle
): Unit

Perform calling of an activity's android.app.Activity#onSaveInstanceState method. The default implementation simply calls through to that method.

Parameters
activity Activity: The activity being saved. This value cannot be null.
outState Bundle: The bundle to pass to the call. This value cannot be null.
outPersistentState PersistableBundle: The persistent bundle to pass to the call. This value cannot be null.

callActivityOnStart

Added in API level 1
open fun callActivityOnStart(activity: Activity!): Unit

Perform calling of an activity's Activity#onStart method. The default implementation simply calls through to that method.

Parameters
activity Activity!: The activity being started.

callActivityOnStop

Added in API level 1
open fun callActivityOnStop(activity: Activity!): Unit

Perform calling of an activity's Activity#onStop method. The default implementation simply calls through to that method.

Parameters
activity Activity!: The activity being stopped.

callActivityOnUserLeaving

Added in API level 3
open fun callActivityOnUserLeaving(activity: Activity!): Unit

Perform calling of an activity's Activity#onUserLeaveHint method. The default implementation simply calls through to that method.

Parameters
activity Activity!: The activity being notified that the user has navigated away

callApplicationOnCreate

Added in API level 1
open fun callApplicationOnCreate(app: Application!): Unit

Perform calling of the application's Application#onCreate method. The default implementation simply calls through to that method.

Note: This method will be called immediately after onCreate(android.os.Bundle). Often instrumentation tests start their test thread in onCreate(); you need to be careful of races between these. (Well between it and everything else, but let's start here.)

Parameters
app Application!: The application being created.

checkMonitorHit

Added in API level 1
open fun checkMonitorHit(
    monitor: Instrumentation.ActivityMonitor!,
    minHits: Int
): Boolean

Test whether an existing ActivityMonitor has been hit. If the monitor has been hit at least minHits times, then it will be removed from the activity monitor list and true returned. Otherwise it is left as-is and false is returned.

Parameters
monitor Instrumentation.ActivityMonitor!: The ActivityMonitor to check.
minHits Int: The minimum number of hits required.
Return
Boolean True if the hit count has been reached, else false.

See Also

    endPerformanceSnapshot

    Added in API level 1
    open fun endPerformanceSnapshot(): Unit

    finish

    Added in API level 1
    open fun finish(
        resultCode: Int,
        results: Bundle!
    ): Unit

    Terminate instrumentation of the application. This will cause the application process to exit, removing this instrumentation from the next time the application is started. If multiple processes are currently running for this instrumentation, all of those processes will be killed.

    Parameters
    resultCode Int: Overall success/failure of instrumentation.
    results Bundle!: Any results to send back to the code that started the instrumentation.

    getAllocCounts

    Added in API level 1
    open fun getAllocCounts(): Bundle!

    Returns a bundle with the current results from the allocation counting.

    getBinderCounts

    Added in API level 1
    open fun getBinderCounts(): Bundle!

    Returns a bundle with the counts for various binder counts for this process. Currently the only two that are reported are the number of send and the number of received transactions.

    getComponentName

    Added in API level 1
    open fun getComponentName(): ComponentName!

    Returns complete component name of this instrumentation.

    Return
    ComponentName! Returns the complete component name for this instrumentation.

    getContext

    Added in API level 1
    open fun getContext(): Context!

    Return the Context of this instrumentation's package. Note that this is often different than the Context of the application being instrumentated, since the instrumentation code often lives is a different package than that of the application it is running against. See getTargetContext to retrieve a Context for the target application.

    Return
    Context! The instrumentation's package context.

    getProcessName

    Added in API level 26
    open fun getProcessName(): String!

    Return the name of the process this instrumentation is running in. Note this should only be used for testing and debugging. If you are thinking about using this to, for example, conditionalize what is initialized in an Application class, it is strongly recommended to instead use lazy initialization (such as a getter for the state that only creates it when requested). This can greatly reduce the work your process does when created for secondary things, such as to receive a broadcast.

    getTargetContext

    Added in API level 1
    open fun getTargetContext(): Context!

    Return a Context for the target application being instrumented. Note that this is often different than the Context of the instrumentation code, since the instrumentation code often lives is a different package than that of the application it is running against. See getContext to retrieve a Context for the instrumentation code.

    Return
    Context! A Context in the target application.

    See Also

    getUiAutomation

    Added in API level 18
    open fun getUiAutomation(): UiAutomation!

    Gets the UiAutomation instance with no flags set.

    Note: The APIs exposed via the returned UiAutomation work across application boundaries while the APIs exposed by the instrumentation do not. For example, Instrumentation#sendPointerSync(MotionEvent) will not allow you to inject the event in an app different from the instrumentation target, while UiAutomation#injectInputEvent(android.view.InputEvent, boolean) will work regardless of the current application.

    A typical test case should be using either the UiAutomation or Instrumentation APIs. Using both APIs at the same time is not a mistake by itself but a client has to be aware of the APIs limitations.

    Equivalent to getUiAutomation(0). If a UiAutomation exists with different flags, the flags on that instance will be changed, and then it will be returned.

    Compatibility mode: This method is infallible for apps targeted for Build.VERSION_CODES#R and earlier versions; for apps targeted for later versions, it will return null if UiAutomation fails to connect. The caller can check the return value and retry on error.

    Return
    UiAutomation! The UI automation instance.

    getUiAutomation

    Added in API level 24
    open fun getUiAutomation(flags: Int): UiAutomation!

    Gets the UiAutomation instance with flags set.

    Note: The APIs exposed via the returned UiAutomation work across application boundaries while the APIs exposed by the instrumentation do not. For example, Instrumentation#sendPointerSync(MotionEvent) will not allow you to inject the event in an app different from the instrumentation target, while UiAutomation#injectInputEvent(android.view.InputEvent, boolean) will work regardless of the current application.

    A typical test case should be using either the UiAutomation or Instrumentation APIs. Using both APIs at the same time is not a mistake by itself but a client has to be aware of the APIs limitations.

    If a UiAutomation exists with different flags, the flags on that instance will be changed, and then it will be returned.

    Compatibility mode: This method is infallible for apps targeted for Build.VERSION_CODES#R and earlier versions; for apps targeted for later versions, it will return null if UiAutomation fails to connect. The caller can check the return value and retry on error.

    Parameters
    flags Int: The flags to be passed to the UiAutomation, for example UiAutomation#FLAG_DONT_SUPPRESS_ACCESSIBILITY_SERVICES, UiAutomation#FLAG_DONT_USE_ACCESSIBILITY. Value is 0, android.app.UiAutomation#FLAG_DONT_SUPPRESS_ACCESSIBILITY_SERVICES, or android.app.UiAutomation#FLAG_DONT_USE_ACCESSIBILITY
    Return
    UiAutomation! The UI automation instance.

    invokeContextMenuAction

    Added in API level 1
    open fun invokeContextMenuAction(
        targetActivity: Activity!,
        id: Int,
        flag: Int
    ): Boolean

    Show the context menu for the currently focused view and executes a particular context menu item.

    Parameters
    targetActivity Activity!: The activity in question.
    id Int: The identifier associated with the context menu item.
    flag Int: Additional flags, if any.
    Return
    Boolean Whether the invocation was successful (for example, it could be false if item is disabled).

    invokeMenuActionSync

    Added in API level 1
    open fun invokeMenuActionSync(
        targetActivity: Activity!,
        id: Int,
        flag: Int
    ): Boolean

    Execute a particular menu item.

    Parameters
    targetActivity Activity!: The activity in question.
    id Int: The identifier associated with the menu item.
    flag Int: Additional flags, if any.
    Return
    Boolean Whether the invocation was successful (for example, it could be false if item is disabled).

    isProfiling

    Added in API level 1
    open fun isProfiling(): Boolean

    Check whether this instrumentation was started with profiling enabled.

    Return
    Boolean Returns true if profiling was enabled when starting, else false.

    newActivity

    Added in API level 1
    open fun newActivity(
        clazz: Class<*>!,
        context: Context!,
        token: IBinder!,
        application: Application!,
        intent: Intent!,
        info: ActivityInfo!,
        title: CharSequence!,
        parent: Activity!,
        id: String!,
        lastNonConfigurationInstance: Any!
    ): Activity!

    Perform instantiation of an Activity object. This method is intended for use with unit tests, such as android.test.ActivityUnitTestCase. The activity will be useable locally but will be missing some of the linkages necessary for use within the system.

    Parameters
    clazz Class<*>!: The Class of the desired Activity
    context Context!: The base context for the activity to use
    token IBinder!: The token for this activity to communicate with
    application Application!: The application object (if any)
    intent Intent!: The intent that started this Activity
    info ActivityInfo!: ActivityInfo from the manifest
    title CharSequence!: The title, typically retrieved from the ActivityInfo record
    parent Activity!: The parent Activity (if any)
    id String!: The embedded Id (if any)
    lastNonConfigurationInstance Any!: Arbitrary object that will be available via Activity.getLastNonConfigurationInstance().
    Return
    Activity! Returns the instantiated activity
    Exceptions
    java.lang.InstantiationException
    java.lang.IllegalAccessException

    newActivity

    Added in API level 1
    open fun newActivity(
        cl: ClassLoader!,
        className: String!,
        intent: Intent!
    ): Activity!

    Perform instantiation of the process's Activity object. The default implementation provides the normal system behavior.

    Parameters
    cl ClassLoader!: The ClassLoader with which to instantiate the object.
    className String!: The name of the class implementing the Activity object.
    intent Intent!: The Intent object that specified the activity class being instantiated.
    Return
    Activity! The newly instantiated Activity object.

    newApplication

    Added in API level 1
    open fun newApplication(
        cl: ClassLoader!,
        className: String!,
        context: Context!
    ): Application!

    Perform instantiation of the process's Application object. The default implementation provides the normal system behavior.

    Parameters
    cl ClassLoader!: The ClassLoader with which to instantiate the object.
    className String!: The name of the class implementing the Application object.
    context Context!: The context to initialize the application with
    Return
    Application! The newly instantiated Application object.

    newApplication

    Added in API level 1
    open static fun newApplication(
        clazz: Class<*>!,
        context: Context!
    ): Application!

    Perform instantiation of the process's Application object. The default implementation provides the normal system behavior.

    Parameters
    clazz Class<*>!: The class used to create an Application object from.
    context Context!: The context to initialize the application with
    Return
    Application! The newly instantiated Application object.

    onCreate

    Added in API level 1
    open fun onCreate(arguments: Bundle!): Unit

    Called when the instrumentation is starting, before any application code has been loaded. Usually this will be implemented to simply call start to begin the instrumentation thread, which will then continue execution in onStart.

    If you do not need your own thread -- that is you are writing your instrumentation to be completely asynchronous (returning to the event loop so that the application can run), you can simply begin your instrumentation here, for example call android.content.Context#startActivity to begin the appropriate first activity of the application.

    Parameters
    arguments Bundle!: Any additional arguments that were supplied when the instrumentation was started.

    onDestroy

    Added in API level 1
    open fun onDestroy(): Unit

    Called when the instrumented application is stopping, after all of the normal application cleanup has occurred.

    onException

    Added in API level 1
    open fun onException(
        obj: Any!,
        e: Throwable!
    ): Boolean

    This is called whenever the system captures an unhandled exception that was thrown by the application. The default implementation simply returns false, allowing normal system handling of the exception to take place.

    Parameters
    obj Any!: The client object that generated the exception. May be an Application, Activity, BroadcastReceiver, Service, or null.
    e Throwable!: The exception that was thrown.
    Return
    Boolean To allow normal system exception process to occur, return false. If true is returned, the system will proceed as if the exception didn't happen.

    onStart

    Added in API level 1
    open fun onStart(): Unit

    Method where the instrumentation thread enters execution. This allows you to run your instrumentation code in a separate thread than the application, so that it can perform blocking operation such as sendKeySync or #startActivitySync.

    You will typically want to call finish() when this function is done, to end your instrumentation.

    removeMonitor

    Added in API level 1
    open fun removeMonitor(monitor: Instrumentation.ActivityMonitor!): Unit

    Remove an ActivityMonitor that was previously added with #addMonitor.

    Parameters
    monitor Instrumentation.ActivityMonitor!: The monitor to remove.

    See Also

      resetInTouchMode

      Added in API level 33
      open fun resetInTouchMode(): Unit

      Resets the touch mode to the device default.

      runOnMainSync

      Added in API level 1
      open fun runOnMainSync(runner: Runnable!): Unit

      Execute a call on the application's main thread, blocking until it is complete. Useful for doing things that are not thread-safe, such as looking at or modifying the view hierarchy.

      Parameters
      runner Runnable!: The code to run on the main thread.

      sendCharacterSync

      Added in API level 1
      open fun sendCharacterSync(keyCode: Int): Unit

      Sends up and down key events with the given key code to the currently focused window, and waits for it to be processed.

      Equivalent to sendKeyDownUpSync(int).

      Parameters
      keyCode Int: The key code of the character to send.

      sendKeyDownUpSync

      Added in API level 1
      open fun sendKeyDownUpSync(keyCode: Int): Unit

      Sends up and down key events with the given key code to the currently focused window, and waits for it to be processed.

      Parameters
      keyCode Int: The key code for the events to send.

      sendKeySync

      Added in API level 1
      open fun sendKeySync(event: KeyEvent!): Unit

      Sends a key event to the currently focused window, and waits for it to be processed.

      This method blocks until the recipient has finished handling the event. Note that the recipient may not have completely finished reacting from the event when this method returns. For example, it may still be in the process of updating its display or UI contents upon reacting to the injected event.

      Parameters
      event KeyEvent!: The event to send to the current focus.

      sendPointerSync

      Added in API level 1
      open fun sendPointerSync(event: MotionEvent!): Unit

      Dispatches a pointer event into a window owned by the instrumented application, and waits for it to be processed.

      If the motion event being injected is targeted at a window that is not owned by the instrumented application, the input injection will fail. See getUiAutomation() for injecting events into all windows.

      This method blocks until the recipient has finished handling the event. Note that the recipient may not have completely finished reacting from the event when this method returns. For example, it may still be in the process of updating its display or UI contents upon reacting to the injected event.

      Parameters
      event MotionEvent!: A motion event describing the pointer action. (As noted in MotionEvent#obtain(long, long, int, float, float, int), be sure to use SystemClock#uptimeMillis() as the timebase.

      sendStatus

      Added in API level 1
      open fun sendStatus(
          resultCode: Int,
          results: Bundle!
      ): Unit

      Provide a status report about the application.

      Parameters
      resultCode Int: Current success/failure of instrumentation.
      results Bundle!: Any results to send back to the code that started the instrumentation.

      sendStringSync

      Added in API level 1
      open fun sendStringSync(text: String!): Unit

      Sends the key events that result in the given text being typed into the currently focused window, and waits for it to be processed.

      Parameters
      text String!: The text to be sent.

      sendTrackballEventSync

      Added in API level 1
      open fun sendTrackballEventSync(event: MotionEvent!): Unit

      Dispatches a trackball event into the currently focused window, and waits for it to be processed.

      This method blocks until the recipient has finished handling the event. Note that the recipient may not have completely finished reacting from the event when this method returns. For example, it may still be in the process of updating its display or UI contents upon reacting to the injected event.

      Parameters
      event MotionEvent!: A motion event describing the trackball action. (As noted in MotionEvent#obtain(long, long, int, float, float, int), be sure to use SystemClock#uptimeMillis() as the timebase.

      setAutomaticPerformanceSnapshots

      Added in API level 1
      open fun setAutomaticPerformanceSnapshots(): Unit

      setInTouchMode

      Added in API level 1
      open fun setInTouchMode(inTouch: Boolean): Unit

      Force the global system in or out of touch mode. This can be used if your instrumentation relies on the UI being in one more or the other when it starts.

      Note: Starting from Android Build.VERSION_CODES#TIRAMISU, this method will only take effect if the instrumentation was sourced from a process with MODIFY_TOUCH_MODE_STATE internal permission granted (shell already have it).

      Parameters
      inTouch Boolean: Set to true to be in touch mode, false to be in focus mode.

      start

      Added in API level 1
      open fun start(): Unit

      Create and start a new thread in which to run instrumentation. This new thread will call to onStart where you can implement the instrumentation.

      startActivitySync

      Added in API level 1
      open fun startActivitySync(intent: Intent!): Activity!

      Start a new activity and wait for it to begin running before returning. In addition to being synchronous, this method as some semantic differences from the standard android.content.Context#startActivity call: the activity component is resolved before talking with the activity manager (its class name is specified in the Intent that this method ultimately starts), and it does not allow you to start activities that run in a different process. In addition, if the given Intent resolves to multiple activities, instead of displaying a dialog for the user to select an activity, an exception will be thrown.

      The function returns as soon as the activity goes idle following the call to its android.app.Activity#onCreate. Generally this means it has gone through the full initialization including Activity#onResume and drawn and displayed its initial window.

      Parameters
      intent Intent!: Description of the activity to start.

      startActivitySync

      Added in API level 28
      open fun startActivitySync(
          intent: Intent,
          options: Bundle?
      ): Activity

      Start a new activity and wait for it to begin running before returning. In addition to being synchronous, this method as some semantic differences from the standard android.content.Context#startActivity call: the activity component is resolved before talking with the activity manager (its class name is specified in the Intent that this method ultimately starts), and it does not allow you to start activities that run in a different process. In addition, if the given Intent resolves to multiple activities, instead of displaying a dialog for the user to select an activity, an exception will be thrown.

      The function returns as soon as the activity goes idle following the call to its android.app.Activity#onCreate. Generally this means it has gone through the full initialization including Activity#onResume and drawn and displayed its initial window.

      Parameters
      intent Intent: Description of the activity to start. This value cannot be null.
      options Bundle?: Additional options for how the Activity should be started. May be null if there are no options. See android.app.ActivityOptions for how to build the Bundle supplied here; there are no supported definitions for building it manually.
      Return
      Activity This value cannot be null.

      startAllocCounting

      Added in API level 1
      Deprecated in API level 23
      open fun startAllocCounting(): Unit

      Deprecated: Deprecated in Java.

      startPerformanceSnapshot

      Added in API level 1
      open fun startPerformanceSnapshot(): Unit

      startProfiling

      Added in API level 1
      open fun startProfiling(): Unit

      This method will start profiling if isProfiling() returns true. You should only call this method if you set the handleProfiling attribute in the manifest file for this Instrumentation to true.

      stopAllocCounting

      Added in API level 1
      Deprecated in API level 23
      open fun stopAllocCounting(): Unit

      Deprecated: Deprecated in Java.

      stopProfiling

      Added in API level 1
      open fun stopProfiling(): Unit

      Stops profiling if isProfiling() returns true.

      waitForIdle

      Added in API level 1
      open fun waitForIdle(recipient: Runnable!): Unit

      Schedule a callback for when the application's main thread goes idle (has no more events to process).

      Parameters
      recipient Runnable!: Called the next time the thread's message queue is idle.

      waitForIdleSync

      Added in API level 1
      open fun waitForIdleSync(): Unit

      Synchronously wait for the application to be idle. Can not be called from the main application thread -- use start to execute instrumentation in its own thread.

      waitForMonitor

      Added in API level 1
      open fun waitForMonitor(monitor: Instrumentation.ActivityMonitor!): Activity!

      Wait for an existing ActivityMonitor to be hit. Once the monitor has been hit, it is removed from the activity monitor list and the first created Activity object that matched it is returned.

      Parameters
      monitor Instrumentation.ActivityMonitor!: The ActivityMonitor to wait for.
      Return
      Activity! The Activity object that matched the monitor.

      waitForMonitorWithTimeout

      Added in API level 1
      open fun waitForMonitorWithTimeout(
          monitor: Instrumentation.ActivityMonitor!,
          timeOut: Long
      ): Activity!

      Wait for an existing ActivityMonitor to be hit till the timeout expires. Once the monitor has been hit, it is removed from the activity monitor list and the first created Activity object that matched it is returned. If the timeout expires, a null object is returned.

      Parameters
      monitor Instrumentation.ActivityMonitor!: The ActivityMonitor to wait for.
      timeOut Long: The timeout value in milliseconds.
      Return
      Activity! The Activity object that matched the monitor.