IsolatedContext
public
class
IsolatedContext
extends ContextWrapper
java.lang.Object | |||
↳ | android.content.Context | ||
↳ | android.content.ContextWrapper | ||
↳ | android.test.IsolatedContext |
This class was deprecated
in API level 24.
New tests should be written using the
Android Testing Support Library.
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(ContentResolver resolver, Context targetContext)
|
Public methods | |
---|---|
boolean
|
bindIsolatedService(Intent service, int flags, String instanceName, Executor executor, ServiceConnection conn)
Variation of |
boolean
|
bindService(Intent service, int flags, Executor executor, ServiceConnection conn)
Same as |
boolean
|
bindService(Intent service, ServiceConnection conn, int flags)
Connects to an application service, creating it if needed. |
int
|
checkUriPermission(Uri uri, int pid, int uid, int modeFlags)
Determine whether a particular process and uid has been granted permission to access a specific URI. |
int
|
checkUriPermission(Uri uri, String readPermission, String writePermission, int pid, int uid, int modeFlags)
Check both a Uri and normal permission. |
List<Intent>
|
getAndClearBroadcastIntents()
Returns the list of intents that were broadcast since the last call to this method. |
AttributionSource
|
getAttributionSource()
|
ContentResolver
|
getContentResolver()
Return a ContentResolver instance for your application's package. |
File
|
getFilesDir()
Returns the absolute path to the directory on the filesystem where files
created with |
Object
|
getSystemService(String name)
Return the handle to a system-level service by name. |
Intent
|
registerReceiver(BroadcastReceiver receiver, IntentFilter filter)
Register a BroadcastReceiver to be run in the main activity thread. |
void
|
sendBroadcast(Intent intent)
Broadcast the given intent to all interested BroadcastReceivers. |
void
|
sendOrderedBroadcast(Intent intent, String receiverPermission)
Broadcast the given intent to all interested BroadcastReceivers, delivering them one at a time to allow more preferred receivers to consume the broadcast before it is delivered to less preferred receivers. |
void
|
unregisterReceiver(BroadcastReceiver receiver)
Unregister a previously registered BroadcastReceiver. |
Inherited methods | |
---|---|
Public constructors
IsolatedContext
public IsolatedContext (ContentResolver resolver, Context targetContext)
Parameters | |
---|---|
resolver |
ContentResolver |
targetContext |
Context |
Public methods
bindIsolatedService
public boolean bindIsolatedService (Intent service, int flags, String instanceName, Executor executor, ServiceConnection conn)
Variation of bindService(Intent, BindServiceFlags, Executor, ServiceConnection)
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 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 ContextWrapper.bindService(Intent, BindServiceFlags, Executor, ServiceConnection) . |
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. |
Returns | |
---|---|
boolean |
Returns success of binding as per bindService(Intent, BindServiceFlags, Executor, ServiceConnection) . |
bindService
public boolean bindService (Intent service, int flags, Executor executor, ServiceConnection conn)
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 Context.BIND_AUTO_CREATE , Context.BIND_DEBUG_UNBIND , Context.BIND_NOT_FOREGROUND , Context.BIND_ABOVE_CLIENT , Context.BIND_ALLOW_OOM_MANAGEMENT , Context.BIND_WAIVE_PRIORITY , Context.BIND_IMPORTANT , Context.BIND_ADJUST_WITH_ACTIVITY , Context.BIND_NOT_PERCEPTIBLE , Context.BIND_ALLOW_ACTIVITY_STARTS , Context.BIND_INCLUDE_CAPABILITIES , Context.BIND_SHARED_ISOLATED_PROCESS , Context.BIND_PACKAGE_ISOLATED_PROCESS , and Context.BIND_EXTERNAL_SERVICE |
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 . |
Returns | |
---|---|
boolean |
The result of the binding as described in
bindService(Intent, ServiceConnection, int) . |
bindService
public boolean bindService (Intent service, ServiceConnection conn, int flags)
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(Intent)
with the arguments containing the command to be
sent, with the service calling its
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(BroadcastReceiver, IntentFilter)
, 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:
|
Returns | |
---|---|
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(ServiceConnection) to release the connection. |
checkUriPermission
public int checkUriPermission (Uri uri, int pid, int uid, int modeFlags)
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 Intent.FLAG_GRANT_READ_URI_PERMISSION , and Intent.FLAG_GRANT_WRITE_URI_PERMISSION |
Returns | |
---|---|
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 PackageManager.PERMISSION_GRANTED , or PackageManager.PERMISSION_DENIED |
checkUriPermission
public int checkUriPermission (Uri uri, String readPermission, String writePermission, int pid, int uid, int modeFlags)
Check both a Uri and normal permission. This allows you to perform
both checkPermission(String, int, int)
and checkUriPermission(Uri, int, int, int)
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 Intent.FLAG_GRANT_READ_URI_PERMISSION , and Intent.FLAG_GRANT_WRITE_URI_PERMISSION |
Returns | |
---|---|
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 PackageManager.PERMISSION_GRANTED , or PackageManager.PERMISSION_DENIED |
getAndClearBroadcastIntents
public List<Intent> getAndClearBroadcastIntents ()
Returns the list of intents that were broadcast since the last call to this method.
Returns | |
---|---|
List<Intent> |
getAttributionSource
public AttributionSource getAttributionSource ()
Returns | |
---|---|
AttributionSource |
This value cannot be null . |
getContentResolver
public ContentResolver getContentResolver ()
Return a ContentResolver instance for your application's package.
Returns | |
---|---|
ContentResolver |
getFilesDir
public File getFilesDir ()
Returns the absolute path to the directory on the filesystem where files
created with openFileOutput(String, int)
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.
Returns | |
---|---|
File |
The path of the directory holding application files. |
getSystemService
public Object getSystemService (String name)
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
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
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
ActivityManager
for interacting with the global activity state of the system. -
WALLPAPER_SERVICE
("wallpaper") - A
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
PowerManager
for controlling power management. -
ALARM_SERVICE
("alarm") - A
AlarmManager
for receiving intents at the time of your choosing. -
NOTIFICATION_SERVICE
("notification") - A
NotificationManager
for informing the user of background events. -
KEYGUARD_SERVICE
("keyguard") - A
KeyguardManager
for controlling keyguard. -
LOCATION_SERVICE
("location") - A
LocationManager
for controlling location (e.g., GPS) updates. -
SEARCH_SERVICE
("search") - A
SearchManager
for handling search. -
VIBRATOR_MANAGER_SERVICE
("vibrator_manager") - A
VibratorManager
for accessing the device vibrators, interacting with individual ones and playing synchronized effects on multiple vibrators. -
VIBRATOR_SERVICE
("vibrator") - A
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
UiModeManager
for controlling UI modes. -
DOWNLOAD_SERVICE
("download") - A
DownloadManager
for requesting HTTP downloads -
BATTERY_SERVICE
("batterymanager") - A
BatteryManager
for managing battery state -
JOB_SCHEDULER_SERVICE
("taskmanager") - A
JobScheduler
for managing scheduled tasks -
NETWORK_STATS_SERVICE
("netstats") - A
NetworkStatsManager
for querying network usage statistics. -
HARDWARE_PROPERTIES_SERVICE
("hardware_properties") - A
HardwarePropertiesManager
for accessing hardware properties. -
DOMAIN_VERIFICATION_SERVICE
("domain_verification") - A
DomainVerificationManager
for accessing web domain approval state. -
DISPLAY_HASH_SERVICE
("display_hash") - A
DisplayHashManager
for management of display hashes. -
ERROR(/#AUTHENTICATION_POLICY_SERVICE)
("authentication_policy") - A
ERROR(/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.
Returns | |
---|---|
Object |
The service or null if the name does not exist. |
registerReceiver
public Intent registerReceiver (BroadcastReceiver receiver, IntentFilter filter)
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 your 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 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 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 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(BroadcastReceiver, IntentFilter)
, 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. |
Returns | |
---|---|
Intent |
The first sticky intent found that matches filter, or null if there are none. |
sendBroadcast
public void sendBroadcast (Intent intent)
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
public void sendOrderedBroadcast (Intent intent, String receiverPermission)
Broadcast the given intent to all interested BroadcastReceivers, delivering them one at a time to allow more preferred receivers to consume the broadcast before it is delivered to less preferred receivers. 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
public void unregisterReceiver (BroadcastReceiver receiver)
Unregister a previously registered BroadcastReceiver. All filters that have been registered for this BroadcastReceiver will be removed.
Parameters | |
---|---|
receiver |
BroadcastReceiver : The BroadcastReceiver to unregister. |