Added in API level 1
Deprecated in API level 24

IsolatedContext


open class IsolatedContext : ContextWrapper
kotlin.Any
   ↳ android.content.Context
   ↳ android.content.ContextWrapper
   ↳ android.test.IsolatedContext

A mock context which prevents its users from talking to the rest of the device while stubbing enough methods to satify code that tries to talk to other packages.

Summary

Inherited constants
Public constructors
IsolatedContext(resolver: ContentResolver!, targetContext: Context!)

Public methods
open Boolean
bindIsolatedService(service: Intent, flags: Int, instanceName: String, executor: Executor, conn: ServiceConnection)

Variation of #bindService that, in the specific case of isolated services, allows the caller to generate multiple instances of a service from a single component declaration.

open Boolean
bindService(service: Intent, conn: ServiceConnection, flags: Int)

Connects to an application service, creating it if needed.

open Boolean
bindService(service: Intent, flags: Int, executor: Executor, conn: ServiceConnection)

Same as bindService(Intent, ServiceConnection, int) with executor to control ServiceConnection callbacks.

open Int
checkUriPermission(uri: Uri!, pid: Int, uid: Int, modeFlags: Int)

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

open Int
checkUriPermission(uri: Uri?, readPermission: String?, writePermission: String?, pid: Int, uid: Int, modeFlags: Int)

Check both a Uri and normal permission.

open MutableList<Intent!>!

Returns the list of intents that were broadcast since the last call to this method.

open AttributionSource

open ContentResolver!

Return a ContentResolver instance for your application's package.

open File!

Returns the absolute path to the directory on the filesystem where files created with openFileOutput are stored.

open Any!

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

open Intent?

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

open Unit

Broadcast the given intent to all interested BroadcastReceivers.

open Unit
sendOrderedBroadcast(intent: Intent!, receiverPermission: String?)

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

open Unit

Unregister a previously registered BroadcastReceiver.

Inherited functions

Public constructors

IsolatedContext

Added in API level 1
IsolatedContext(
    resolver: ContentResolver!,
    targetContext: Context!)

Public methods

bindIsolatedService

Added in API level 29
Deprecated in API level 24
open fun bindIsolatedService(
    service: Intent,
    flags: Int,
    instanceName: String,
    executor: Executor,
    conn: ServiceConnection
): Boolean

Deprecated: Deprecated in Java.

Variation of #bindService that, in the specific case of isolated services, allows the caller to generate multiple instances of a service from a single component declaration. In other words, you can use this to bind to a service that has specified android.R.attr#isolatedProcess and, in addition to the existing behavior of running in an isolated process, you can also through the arguments here have the system bring up multiple concurrent processes hosting their own instances of that service. The instanceName you provide here identifies the different instances, and you can use updateServiceGroup(android.content.ServiceConnection,int,int) to tell the system how it should manage each of these instances.

Parameters
service Intent: Identifies the service to connect to. The Intent must specify an explicit component name.
This value cannot be null.
flags Int: Operation options for the binding as per #bindService.
instanceName String: Unique identifier for the service instance. Each unique name here will result in a different service instance being created. Identifiers must only contain ASCII letters, digits, underscores, and periods.
This value cannot be null.
executor Executor: Callbacks on ServiceConnection will be called on executor. Must use same instance for the same instance of ServiceConnection.
This value cannot be null.
Callback and listener events are dispatched through this Executor, providing an easy way to control which thread is used. To dispatch events through the main thread of your application, you can use Context.getMainExecutor(). Otherwise, provide an Executor that dispatches to an appropriate thread.
conn ServiceConnection: Receives information as the service is started and stopped. This must be a valid ServiceConnection object; it must not be null.
Return
Boolean Returns success of binding as per #bindService.
Exceptions
java.lang.IllegalArgumentException If the instanceName is invalid.
java.lang.SecurityException If the caller does not have permission to access the service

bindService

Added in API level 1
open fun bindService(
    service: Intent,
    conn: ServiceConnection,
    flags: Int
): Boolean

Deprecated: Deprecated in Java.

Connects to an application service, creating it if needed. This defines a dependency between your application and the service. The given conn will receive the service object when it is created and be told if it dies and restarts. The service will be considered required by the system only for as long as the calling context exists. For example, if this Context is an Activity that is stopped, the service will not be required to continue running until the Activity is resumed.

If the service does not support binding, it may return null from its onBind() method. If it does, then the ServiceConnection's onNullBinding() method will be invoked instead of onServiceConnected().

Note: This method cannot be called from a BroadcastReceiver component. A pattern you can use to communicate from a BroadcastReceiver to a Service is to call startService with the arguments containing the command to be sent, with the service calling its android.app.Service#stopSelf(int) method when done executing that command. See the API demo App/Service/Service Start Arguments Controller for an illustration of this. It is okay, however, to use this method from a BroadcastReceiver that has been registered with #registerReceiver, since the lifetime of this BroadcastReceiver is tied to another object (the one that registered it).

This method only accepts a int type flag, to pass in a long type flag, call bindService(android.content.Intent,android.content.ServiceConnection,android.content.Context.BindServiceFlags) instead.

Parameters
service Intent: Identifies the service to connect to. The Intent must specify an explicit component name.
This value cannot be null.
conn ServiceConnection: Receives information as the service is started and stopped. This must be a valid ServiceConnection object; it must not be null.
flags Int: Operation options for the binding. Can be:
Return
Boolean true if the system is in the process of bringing up a service that your client has permission to bind to; false if the system couldn't find the service or if your client doesn't have permission to bind to it. Regardless of the return value, you should later call unbindService to release the connection.
Exceptions
java.lang.SecurityException If the caller does not have permission to access the service or the service cannot be found. Call unbindService to release the connection when this exception is thrown.

bindService

Added in API level 29
Deprecated in API level 24
open fun bindService(
    service: Intent,
    flags: Int,
    executor: Executor,
    conn: ServiceConnection
): Boolean

Deprecated: Deprecated in Java.

Same as bindService(Intent, ServiceConnection, int) with executor to control ServiceConnection callbacks.

This method only accepts a 32 bits flag, to pass in a 64 bits flag, call bindService(android.content.Intent,android.content.Context.BindServiceFlags,java.util.concurrent.Executor,android.content.ServiceConnection) instead.

Parameters
service Intent: This value cannot be null.
flags Int: Value is either 0 or a combination of the following:
executor Executor: Callbacks on ServiceConnection will be called on executor. Must use same instance for the same instance of ServiceConnection.
This value cannot be null.
Callback and listener events are dispatched through this Executor, providing an easy way to control which thread is used. To dispatch events through the main thread of your application, you can use Context.getMainExecutor(). Otherwise, provide an Executor that dispatches to an appropriate thread.
conn ServiceConnection: This value cannot be null.
Return
Boolean The result of the binding as described in bindService(Intent, ServiceConnection, int).

checkUriPermission

Added in API level 1
open fun checkUriPermission(
    uri: Uri!,
    pid: Int,
    uid: Int,
    modeFlags: Int
): Int

Deprecated: Deprecated in Java.

Determine whether a particular process and uid has been granted permission to access a specific URI. This only checks for permissions that have been explicitly granted -- if the given process/uid has more general access to the URI's content provider then this check will always fail.

Parameters
uri Uri!: The uri that is being checked.
pid Int: The process ID being checked against. Must be > 0.
uid Int: The UID being checked against. A uid of 0 is the root user, which will pass every permission check.
modeFlags Int: The access modes to check.
Value is either 0 or a combination of the following:
Return
Int PackageManager.PERMISSION_GRANTED if the given pid/uid is allowed to access that uri, or PackageManager.PERMISSION_DENIED if it is not.
Value is one of the following:

checkUriPermission

Added in API level 1
open fun checkUriPermission(
    uri: Uri?,
    readPermission: String?,
    writePermission: String?,
    pid: Int,
    uid: Int,
    modeFlags: Int
): Int

Deprecated: Deprecated in Java.

Check both a Uri and normal permission. This allows you to perform both checkPermission and #checkUriPermission in one call.

Parameters
uri Uri?: This value may be null.
readPermission String?: This value may be null.
writePermission String?: This value may be null.
pid Int: The process ID being checked against. Must be > 0.
uid Int: The UID being checked against. A uid of 0 is the root user, which will pass every permission check.
modeFlags Int: The access modes to check.
Value is either 0 or a combination of the following:
Return
Int PackageManager.PERMISSION_GRANTED if the caller is allowed to access that uri or holds one of the given permissions, or PackageManager.PERMISSION_DENIED if it is not.
Value is one of the following:

getAndClearBroadcastIntents

Added in API level 1
open fun getAndClearBroadcastIntents(): MutableList<Intent!>!

Deprecated: Deprecated in Java.

Returns the list of intents that were broadcast since the last call to this method.

getAttributionSource

Added in API level 31
Deprecated in API level 24
open fun getAttributionSource(): AttributionSource

Deprecated: Deprecated in Java.

Return
AttributionSource This value cannot be null.

getContentResolver

Added in API level 1
open fun getContentResolver(): ContentResolver!

Deprecated: Deprecated in Java.

Return a ContentResolver instance for your application's package.

getFilesDir

Added in API level 1
open fun getFilesDir(): File!

Deprecated: Deprecated in Java.

Returns the absolute path to the directory on the filesystem where files created with openFileOutput are stored.

The returned path may change over time if the calling app is moved to an adopted storage device, so only relative paths should be persisted.

No additional permissions are required for the calling app to read or write files under the returned path.

Return
File! The path of the directory holding application files.

getSystemService

Added in API level 1
open fun getSystemService(name: String): Any!

Deprecated: Deprecated in Java.

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 with createWindowContext(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 with createWindowContext(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 with createWindowContext(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.

Parameters
name String: The name of the desired service.
Value is one of the following:
Return
Any! The service or null if the name does not exist.

registerReceiver

Added in API level 1
open fun registerReceiver(
    receiver: BroadcastReceiver?,
    filter: IntentFilter!
): Intent?

Deprecated: Deprecated in Java.

Register a BroadcastReceiver to be run in the main activity thread. The receiver will be called with any broadcast Intent that matches filter, in the main application thread.

The system may broadcast Intents that are "sticky" -- these stay around after the broadcast has finished, to be sent to any later registrations. If your IntentFilter matches one of these sticky Intents, that Intent will be returned by this function and sent to your receiver as if it had just been broadcast.

There may be multiple sticky Intents that match filter, in which case each of these will be sent to receiver. In this case, only one of these can be returned directly by the function; which of these that is returned is arbitrarily decided by the system.

If you know the Intent you are registering for is sticky, you can supply null for your receiver. In this case, no receiver is registered -- the function simply returns the sticky Intent that matches filter. In the case of multiple matches, the same rules as described above apply.

See BroadcastReceiver for more information on Intent broadcasts.

As of android.os.Build.VERSION_CODES#UPSIDE_DOWN_CAKE, the system can place context-registered broadcasts in a queue while the app is in the cached state. When the app leaves the cached state, such as returning to the foreground, the system delivers any queued broadcasts. Multiple instances of certain broadcasts might be merged into one broadcast.

As of android.os.Build.VERSION_CODES#ICE_CREAM_SANDWICH, receivers registered with this method will correctly respect the Intent.setPackage(String) specified for an Intent being broadcast. Prior to that, it would be ignored and delivered to all matching registered receivers. Be careful if using this for security.

For apps targeting android.os.Build.VERSION_CODES#UPSIDE_DOWN_CAKE, either RECEIVER_EXPORTED or RECEIVER_NOT_EXPORTED must be specified if the receiver is not being registered for system broadcasts or a SecurityException will be thrown. See registerReceiver(android.content.BroadcastReceiver,android.content.IntentFilter,int) to register a receiver with flags.

Note: this method cannot be called from a BroadcastReceiver component; that is, from a BroadcastReceiver that is declared in an application's manifest. It is okay, however, to call this method from another BroadcastReceiver that has itself been registered at run time with #registerReceiver, since the lifetime of such a registered BroadcastReceiver is tied to the object that registered it.

Parameters
receiver BroadcastReceiver?: This value may be null.
filter IntentFilter!: Selects the Intent broadcasts to be received.
Return
Intent? The first sticky intent found that matches filter, or null if there are none.

sendBroadcast

Added in API level 1
open fun sendBroadcast(intent: Intent!): Unit

Deprecated: Deprecated in Java.

Broadcast the given intent to all interested BroadcastReceivers. This call is asynchronous; it returns immediately, and you will continue executing while the receivers are run. No results are propagated from receivers and receivers can not abort the broadcast. If you want to allow receivers to propagate results or abort the broadcast, you must send an ordered broadcast using sendOrderedBroadcast(android.content.Intent,java.lang.String).

See BroadcastReceiver for more information on Intent broadcasts.

Parameters
intent Intent!: The Intent to broadcast; all receivers matching this Intent will receive the broadcast.

sendOrderedBroadcast

Added in API level 1
open fun sendOrderedBroadcast(
    intent: Intent!,
    receiverPermission: String?
): Unit

Deprecated: Deprecated in Java.

Broadcast the given intent to all interested BroadcastReceivers, delivering them one at a time to allow more preferred receivers to consume the broadcast before it is delivered to less preferred receivers. This call is asynchronous; it returns immediately, and you will continue executing while the receivers are run.

See BroadcastReceiver for more information on Intent broadcasts.

Parameters
intent Intent!: The Intent to broadcast; all receivers matching this Intent will receive the broadcast.
receiverPermission String?: This value may be null.

unregisterReceiver

Added in API level 1
open fun unregisterReceiver(receiver: BroadcastReceiver!): Unit

Deprecated: Deprecated in Java.

Unregister a previously registered BroadcastReceiver. All filters that have been registered for this BroadcastReceiver will be removed.

Parameters
receiver BroadcastReceiver!: The BroadcastReceiver to unregister.
Exceptions
java.lang.IllegalArgumentException if the receiver was not previously registered or already unregistered.