2 * Copyright (C) 2006 The Android Open Source Project
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
17 package android.content;
19 import android.annotation.AttrRes;
20 import android.annotation.CheckResult;
21 import android.annotation.ColorInt;
22 import android.annotation.ColorRes;
23 import android.annotation.DrawableRes;
24 import android.annotation.IntDef;
25 import android.annotation.NonNull;
26 import android.annotation.Nullable;
27 import android.annotation.RequiresPermission;
28 import android.annotation.StringDef;
29 import android.annotation.StringRes;
30 import android.annotation.StyleRes;
31 import android.annotation.StyleableRes;
32 import android.annotation.SystemApi;
33 import android.annotation.TestApi;
34 import android.annotation.UserIdInt;
35 import android.app.IApplicationThread;
36 import android.app.IServiceConnection;
37 import android.app.Notification;
38 import android.app.VrManager;
39 import android.content.pm.ApplicationInfo;
40 import android.content.pm.PackageManager;
41 import android.content.res.AssetManager;
42 import android.content.res.ColorStateList;
43 import android.content.res.Configuration;
44 import android.content.res.Resources;
45 import android.content.res.TypedArray;
46 import android.database.DatabaseErrorHandler;
47 import android.database.sqlite.SQLiteDatabase;
48 import android.database.sqlite.SQLiteDatabase.CursorFactory;
49 import android.graphics.Bitmap;
50 import android.graphics.drawable.Drawable;
51 import android.net.Uri;
52 import android.os.Bundle;
53 import android.os.Environment;
54 import android.os.Handler;
55 import android.os.IBinder;
56 import android.os.Looper;
57 import android.os.StatFs;
58 import android.os.UserHandle;
59 import android.os.UserManager;
60 import android.provider.MediaStore;
61 import android.util.AttributeSet;
62 import android.view.Display;
63 import android.view.DisplayAdjustments;
64 import android.view.View;
65 import android.view.ViewDebug;
66 import android.view.WindowManager;
67 import android.view.textclassifier.TextClassificationManager;
70 import java.io.FileInputStream;
71 import java.io.FileNotFoundException;
72 import java.io.FileOutputStream;
73 import java.io.IOException;
74 import java.io.InputStream;
75 import java.lang.annotation.Retention;
76 import java.lang.annotation.RetentionPolicy;
79 * Interface to global information about an application environment. This is
80 * an abstract class whose implementation is provided by
81 * the Android system. It
82 * allows access to application-specific resources and classes, as well as
83 * up-calls for application-level operations such as launching activities,
84 * broadcasting and receiving intents, etc.
86 public abstract class Context {
88 * File creation mode: the default mode, where the created file can only
89 * be accessed by the calling application (or all applications sharing the
92 public static final int MODE_PRIVATE = 0x0000;
95 * File creation mode: allow all other applications to have read access to
98 * As of {@link android.os.Build.VERSION_CODES#N} attempting to use this
99 * mode will throw a {@link SecurityException}.
101 * @deprecated Creating world-readable files is very dangerous, and likely
102 * to cause security holes in applications. It is strongly
103 * discouraged; instead, applications should use more formal
104 * mechanism for interactions such as {@link ContentProvider},
105 * {@link BroadcastReceiver}, and {@link android.app.Service}.
106 * There are no guarantees that this access mode will remain on
107 * a file, such as when it goes through a backup and restore.
108 * @see android.support.v4.content.FileProvider
109 * @see Intent#FLAG_GRANT_WRITE_URI_PERMISSION
112 public static final int MODE_WORLD_READABLE = 0x0001;
115 * File creation mode: allow all other applications to have write access to
118 * As of {@link android.os.Build.VERSION_CODES#N} attempting to use this
119 * mode will throw a {@link SecurityException}.
121 * @deprecated Creating world-writable files is very dangerous, and likely
122 * to cause security holes in applications. It is strongly
123 * discouraged; instead, applications should use more formal
124 * mechanism for interactions such as {@link ContentProvider},
125 * {@link BroadcastReceiver}, and {@link android.app.Service}.
126 * There are no guarantees that this access mode will remain on
127 * a file, such as when it goes through a backup and restore.
128 * @see android.support.v4.content.FileProvider
129 * @see Intent#FLAG_GRANT_WRITE_URI_PERMISSION
132 public static final int MODE_WORLD_WRITEABLE = 0x0002;
135 * File creation mode: for use with {@link #openFileOutput}, if the file
136 * already exists then write data to the end of the existing file
137 * instead of erasing it.
138 * @see #openFileOutput
140 public static final int MODE_APPEND = 0x8000;
143 * SharedPreference loading flag: when set, the file on disk will
144 * be checked for modification even if the shared preferences
145 * instance is already loaded in this process. This behavior is
146 * sometimes desired in cases where the application has multiple
147 * processes, all writing to the same SharedPreferences file.
148 * Generally there are better forms of communication between
151 * <p>This was the legacy (but undocumented) behavior in and
152 * before Gingerbread (Android 2.3) and this flag is implied when
153 * targetting such releases. For applications targetting SDK
154 * versions <em>greater than</em> Android 2.3, this flag must be
155 * explicitly set if desired.
157 * @see #getSharedPreferences
159 * @deprecated MODE_MULTI_PROCESS does not work reliably in
160 * some versions of Android, and furthermore does not provide any
161 * mechanism for reconciling concurrent modifications across
162 * processes. Applications should not attempt to use it. Instead,
163 * they should use an explicit cross-process data management
164 * approach such as {@link android.content.ContentProvider ContentProvider}.
167 public static final int MODE_MULTI_PROCESS = 0x0004;
170 * Database open flag: when set, the database is opened with write-ahead
171 * logging enabled by default.
173 * @see #openOrCreateDatabase(String, int, CursorFactory)
174 * @see #openOrCreateDatabase(String, int, CursorFactory, DatabaseErrorHandler)
175 * @see SQLiteDatabase#enableWriteAheadLogging
177 public static final int MODE_ENABLE_WRITE_AHEAD_LOGGING = 0x0008;
180 * Database open flag: when set, the database is opened without support for
181 * localized collators.
183 * @see #openOrCreateDatabase(String, int, CursorFactory)
184 * @see #openOrCreateDatabase(String, int, CursorFactory, DatabaseErrorHandler)
185 * @see SQLiteDatabase#NO_LOCALIZED_COLLATORS
187 public static final int MODE_NO_LOCALIZED_COLLATORS = 0x0010;
196 BIND_ALLOW_OOM_MANAGEMENT,
199 BIND_ADJUST_WITH_ACTIVITY
201 @Retention(RetentionPolicy.SOURCE)
202 public @interface BindServiceFlags {}
205 * Flag for {@link #bindService}: automatically create the service as long
206 * as the binding exists. Note that while this will create the service,
207 * its {@link android.app.Service#onStartCommand}
208 * method will still only be called due to an
209 * explicit call to {@link #startService}. Even without that, though,
210 * this still provides you with access to the service object while the
211 * service is created.
213 * <p>Note that prior to {@link android.os.Build.VERSION_CODES#ICE_CREAM_SANDWICH},
214 * not supplying this flag would also impact how important the system
215 * consider's the target service's process to be. When set, the only way
216 * for it to be raised was by binding from a service in which case it will
217 * only be important when that activity is in the foreground. Now to
218 * achieve this behavior you must explicitly supply the new flag
219 * {@link #BIND_ADJUST_WITH_ACTIVITY}. For compatibility, old applications
220 * that don't specify {@link #BIND_AUTO_CREATE} will automatically have
221 * the flags {@link #BIND_WAIVE_PRIORITY} and
222 * {@link #BIND_ADJUST_WITH_ACTIVITY} set for them in order to achieve
225 public static final int BIND_AUTO_CREATE = 0x0001;
228 * Flag for {@link #bindService}: include debugging help for mismatched
229 * calls to unbind. When this flag is set, the callstack of the following
230 * {@link #unbindService} call is retained, to be printed if a later
231 * incorrect unbind call is made. Note that doing this requires retaining
232 * information about the binding that was made for the lifetime of the app,
233 * resulting in a leak -- this should only be used for debugging.
235 public static final int BIND_DEBUG_UNBIND = 0x0002;
238 * Flag for {@link #bindService}: don't allow this binding to raise
239 * the target service's process to the foreground scheduling priority.
240 * It will still be raised to at least the same memory priority
241 * as the client (so that its process will not be killable in any
242 * situation where the client is not killable), but for CPU scheduling
243 * purposes it may be left in the background. This only has an impact
244 * in the situation where the binding client is a foreground process
245 * and the target service is in a background process.
247 public static final int BIND_NOT_FOREGROUND = 0x0004;
250 * Flag for {@link #bindService}: indicates that the client application
251 * binding to this service considers the service to be more important than
252 * the app itself. When set, the platform will try to have the out of
253 * memory killer kill the app before it kills the service it is bound to, though
254 * this is not guaranteed to be the case.
256 public static final int BIND_ABOVE_CLIENT = 0x0008;
259 * Flag for {@link #bindService}: allow the process hosting the bound
260 * service to go through its normal memory management. It will be
261 * treated more like a running service, allowing the system to
262 * (temporarily) expunge the process if low on memory or for some other
263 * whim it may have, and being more aggressive about making it a candidate
264 * to be killed (and restarted) if running for a long time.
266 public static final int BIND_ALLOW_OOM_MANAGEMENT = 0x0010;
269 * Flag for {@link #bindService}: don't impact the scheduling or
270 * memory management priority of the target service's hosting process.
271 * Allows the service's process to be managed on the background LRU list
272 * just like a regular application process in the background.
274 public static final int BIND_WAIVE_PRIORITY = 0x0020;
277 * Flag for {@link #bindService}: this service is very important to
278 * the client, so should be brought to the foreground process level
279 * when the client is. Normally a process can only be raised to the
280 * visibility level by a client, even if that client is in the foreground.
282 public static final int BIND_IMPORTANT = 0x0040;
285 * Flag for {@link #bindService}: If binding from an activity, allow the
286 * target service's process importance to be raised based on whether the
287 * activity is visible to the user, regardless whether another flag is
288 * used to reduce the amount that the client process's overall importance
289 * is used to impact it.
291 public static final int BIND_ADJUST_WITH_ACTIVITY = 0x0080;
294 * @hide Flag for {@link #bindService}: allows application hosting service to manage whitelists
295 * such as temporary allowing a {@code PendingIntent} to bypass Power Save mode.
297 public static final int BIND_ALLOW_WHITELIST_MANAGEMENT = 0x01000000;
300 * @hide Flag for {@link #bindService}: Like {@link #BIND_FOREGROUND_SERVICE},
301 * but only applies while the device is awake.
303 public static final int BIND_FOREGROUND_SERVICE_WHILE_AWAKE = 0x02000000;
306 * @hide Flag for {@link #bindService}: For only the case where the binding
307 * is coming from the system, set the process state to FOREGROUND_SERVICE
308 * instead of the normal maximum of IMPORTANT_FOREGROUND. That is, this is
309 * saying that the process shouldn't participate in the normal power reduction
310 * modes (removing network access etc).
312 public static final int BIND_FOREGROUND_SERVICE = 0x04000000;
315 * @hide Flag for {@link #bindService}: Treat the binding as hosting
316 * an activity, an unbinding as the activity going in the background.
317 * That is, when unbinding, the process when empty will go on the activity
318 * LRU list instead of the regular one, keeping it around more aggressively
319 * than it otherwise would be. This is intended for use with IMEs to try
320 * to keep IME processes around for faster keyboard switching.
322 public static final int BIND_TREAT_LIKE_ACTIVITY = 0x08000000;
325 * @hide An idea that is not yet implemented.
326 * Flag for {@link #bindService}: If binding from an activity, consider
327 * this service to be visible like the binding activity is. That is,
328 * it will be treated as something more important to keep around than
329 * invisible background activities. This will impact the number of
330 * recent activities the user can switch between without having them
331 * restart. There is no guarantee this will be respected, as the system
332 * tries to balance such requests from one app vs. the importantance of
333 * keeping other apps around.
335 public static final int BIND_VISIBLE = 0x10000000;
339 * Flag for {@link #bindService}: Consider this binding to be causing the target
340 * process to be showing UI, so it will be do a UI_HIDDEN memory trim when it goes
343 public static final int BIND_SHOWING_UI = 0x20000000;
346 * Flag for {@link #bindService}: Don't consider the bound service to be
347 * visible, even if the caller is visible.
350 public static final int BIND_NOT_VISIBLE = 0x40000000;
353 * Flag for {@link #bindService}: The service being bound is an
354 * {@link android.R.attr#isolatedProcess isolated},
355 * {@link android.R.attr#externalService external} service. This binds the service into the
356 * calling application's package, rather than the package in which the service is declared.
358 * When using this flag, the code for the service being bound will execute under the calling
359 * application's package name and user ID. Because the service must be an isolated process,
360 * it will not have direct access to the application's data, though.
362 * The purpose of this flag is to allow applications to provide services that are attributed
363 * to the app using the service, rather than the application providing the service.
366 public static final int BIND_EXTERNAL_SERVICE = 0x80000000;
369 * Returns an AssetManager instance for the application's package.
371 * <strong>Note:</strong> Implementations of this method should return
372 * an AssetManager instance that is consistent with the Resources instance
373 * returned by {@link #getResources()}. For example, they should share the
374 * same {@link Configuration} object.
376 * @return an AssetManager instance for the application's package
377 * @see #getResources()
379 public abstract AssetManager getAssets();
382 * Returns a Resources instance for the application's package.
384 * <strong>Note:</strong> Implementations of this method should return
385 * a Resources instance that is consistent with the AssetManager instance
386 * returned by {@link #getAssets()}. For example, they should share the
387 * same {@link Configuration} object.
389 * @return a Resources instance for the application's package
392 public abstract Resources getResources();
394 /** Return PackageManager instance to find global package information. */
395 public abstract PackageManager getPackageManager();
397 /** Return a ContentResolver instance for your application's package. */
398 public abstract ContentResolver getContentResolver();
401 * Return the Looper for the main thread of the current process. This is
402 * the thread used to dispatch calls to application components (activities,
405 * By definition, this method returns the same result as would be obtained
406 * by calling {@link Looper#getMainLooper() Looper.getMainLooper()}.
409 * @return The main looper.
411 public abstract Looper getMainLooper();
414 * Return the context of the single, global Application object of the
415 * current process. This generally should only be used if you need a
416 * Context whose lifecycle is separate from the current context, that is
417 * tied to the lifetime of the process rather than the current component.
419 * <p>Consider for example how this interacts with
420 * {@link #registerReceiver(BroadcastReceiver, IntentFilter)}:
422 * <li> <p>If used from an Activity context, the receiver is being registered
423 * within that activity. This means that you are expected to unregister
424 * before the activity is done being destroyed; in fact if you do not do
425 * so, the framework will clean up your leaked registration as it removes
426 * the activity and log an error. Thus, if you use the Activity context
427 * to register a receiver that is static (global to the process, not
428 * associated with an Activity instance) then that registration will be
429 * removed on you at whatever point the activity you used is destroyed.
430 * <li> <p>If used from the Context returned here, the receiver is being
431 * registered with the global state associated with your application. Thus
432 * it will never be unregistered for you. This is necessary if the receiver
433 * is associated with static data, not a particular component. However
434 * using the ApplicationContext elsewhere can easily lead to serious leaks
435 * if you forget to unregister, unbind, etc.
438 public abstract Context getApplicationContext();
440 /** Non-activity related accessibility ids are unique in the app */
441 private static int sLastAccessibilityId = View.NO_ID;
444 * Gets the next accessibility ID.
446 * <p>All IDs will be smaller or the same as {@link View#LAST_APP_ACCESSIBILITY_ID}. All IDs
447 * returned will be unique.
449 * @return A ID that is unique in the process
453 public int getNextAccessibilityId() {
454 if (sLastAccessibilityId == View.LAST_APP_ACCESSIBILITY_ID - 1) {
455 sLastAccessibilityId = View.NO_ID;
458 sLastAccessibilityId++;
460 return sLastAccessibilityId;
464 * Add a new {@link ComponentCallbacks} to the base application of the
465 * Context, which will be called at the same times as the ComponentCallbacks
466 * methods of activities and other components are called. Note that you
467 * <em>must</em> be sure to use {@link #unregisterComponentCallbacks} when
468 * appropriate in the future; this will not be removed for you.
470 * @param callback The interface to call. This can be either a
471 * {@link ComponentCallbacks} or {@link ComponentCallbacks2} interface.
473 public void registerComponentCallbacks(ComponentCallbacks callback) {
474 getApplicationContext().registerComponentCallbacks(callback);
478 * Remove a {@link ComponentCallbacks} object that was previously registered
479 * with {@link #registerComponentCallbacks(ComponentCallbacks)}.
481 public void unregisterComponentCallbacks(ComponentCallbacks callback) {
482 getApplicationContext().unregisterComponentCallbacks(callback);
486 * Return a localized, styled CharSequence from the application's package's
487 * default string table.
489 * @param resId Resource id for the CharSequence text
491 public final CharSequence getText(@StringRes int resId) {
492 return getResources().getText(resId);
496 * Returns a localized string from the application's package's
497 * default string table.
499 * @param resId Resource id for the string
500 * @return The string data associated with the resource, stripped of styled
504 public final String getString(@StringRes int resId) {
505 return getResources().getString(resId);
509 * Returns a localized formatted string from the application's package's
510 * default string table, substituting the format arguments as defined in
511 * {@link java.util.Formatter} and {@link java.lang.String#format}.
513 * @param resId Resource id for the format string
514 * @param formatArgs The format arguments that will be used for
516 * @return The string data associated with the resource, formatted and
517 * stripped of styled text information.
520 public final String getString(@StringRes int resId, Object... formatArgs) {
521 return getResources().getString(resId, formatArgs);
525 * Returns a color associated with a particular resource ID and styled for
528 * @param id The desired resource identifier, as generated by the aapt
529 * tool. This integer encodes the package, type, and resource
530 * entry. The value 0 is an invalid identifier.
531 * @return A single color value in the form 0xAARRGGBB.
532 * @throws android.content.res.Resources.NotFoundException if the given ID
536 public final int getColor(@ColorRes int id) {
537 return getResources().getColor(id, getTheme());
541 * Returns a drawable object associated with a particular resource ID and
542 * styled for the current theme.
544 * @param id The desired resource identifier, as generated by the aapt
545 * tool. This integer encodes the package, type, and resource
546 * entry. The value 0 is an invalid identifier.
547 * @return An object that can be used to draw this resource, or
548 * {@code null} if the resource could not be resolved.
549 * @throws android.content.res.Resources.NotFoundException if the given ID
553 public final Drawable getDrawable(@DrawableRes int id) {
554 return getResources().getDrawable(id, getTheme());
558 * Returns a color state list associated with a particular resource ID and
559 * styled for the current theme.
561 * @param id The desired resource identifier, as generated by the aapt
562 * tool. This integer encodes the package, type, and resource
563 * entry. The value 0 is an invalid identifier.
564 * @return A color state list, or {@code null} if the resource could not be
566 * @throws android.content.res.Resources.NotFoundException if the given ID
570 public final ColorStateList getColorStateList(@ColorRes int id) {
571 return getResources().getColorStateList(id, getTheme());
575 * Set the base theme for this context. Note that this should be called
576 * before any views are instantiated in the Context (for example before
577 * calling {@link android.app.Activity#setContentView} or
578 * {@link android.view.LayoutInflater#inflate}).
580 * @param resid The style resource describing the theme.
582 public abstract void setTheme(@StyleRes int resid);
584 /** @hide Needed for some internal implementation... not public because
585 * you can't assume this actually means anything. */
586 public int getThemeResId() {
591 * Return the Theme object associated with this Context.
593 @ViewDebug.ExportedProperty(deepExport = true)
594 public abstract Resources.Theme getTheme();
597 * Retrieve styled attribute information in this Context's theme. See
598 * {@link android.content.res.Resources.Theme#obtainStyledAttributes(int[])}
599 * for more information.
601 * @see android.content.res.Resources.Theme#obtainStyledAttributes(int[])
603 public final TypedArray obtainStyledAttributes(@StyleableRes int[] attrs) {
604 return getTheme().obtainStyledAttributes(attrs);
608 * Retrieve styled attribute information in this Context's theme. See
609 * {@link android.content.res.Resources.Theme#obtainStyledAttributes(int, int[])}
610 * for more information.
612 * @see android.content.res.Resources.Theme#obtainStyledAttributes(int, int[])
614 public final TypedArray obtainStyledAttributes(
615 @StyleRes int resid, @StyleableRes int[] attrs) throws Resources.NotFoundException {
616 return getTheme().obtainStyledAttributes(resid, attrs);
620 * Retrieve styled attribute information in this Context's theme. See
621 * {@link android.content.res.Resources.Theme#obtainStyledAttributes(AttributeSet, int[], int, int)}
622 * for more information.
624 * @see android.content.res.Resources.Theme#obtainStyledAttributes(AttributeSet, int[], int, int)
626 public final TypedArray obtainStyledAttributes(
627 AttributeSet set, @StyleableRes int[] attrs) {
628 return getTheme().obtainStyledAttributes(set, attrs, 0, 0);
632 * Retrieve styled attribute information in this Context's theme. See
633 * {@link android.content.res.Resources.Theme#obtainStyledAttributes(AttributeSet, int[], int, int)}
634 * for more information.
636 * @see android.content.res.Resources.Theme#obtainStyledAttributes(AttributeSet, int[], int, int)
638 public final TypedArray obtainStyledAttributes(
639 AttributeSet set, @StyleableRes int[] attrs, @AttrRes int defStyleAttr,
640 @StyleRes int defStyleRes) {
641 return getTheme().obtainStyledAttributes(
642 set, attrs, defStyleAttr, defStyleRes);
646 * Return a class loader you can use to retrieve classes in this package.
648 public abstract ClassLoader getClassLoader();
650 /** Return the name of this application's package. */
651 public abstract String getPackageName();
653 /** @hide Return the name of the base context this context is derived from. */
654 public abstract String getBasePackageName();
656 /** @hide Return the package name that should be used for app ops calls from
657 * this context. This is the same as {@link #getBasePackageName()} except in
658 * cases where system components are loaded into other app processes, in which
659 * case this will be the name of the primary package in that process (so that app
660 * ops uid verification will work with the name). */
661 public abstract String getOpPackageName();
663 /** Return the full application info for this context's package. */
664 public abstract ApplicationInfo getApplicationInfo();
667 * Return the full path to this context's primary Android package.
668 * The Android package is a ZIP file which contains the application's
671 * <p>Note: this is not generally useful for applications, since they should
672 * not be directly accessing the file system.
674 * @return String Path to the resources.
676 public abstract String getPackageResourcePath();
679 * Return the full path to this context's primary Android package.
680 * The Android package is a ZIP file which contains application's
681 * primary code and assets.
683 * <p>Note: this is not generally useful for applications, since they should
684 * not be directly accessing the file system.
686 * @return String Path to the code and assets.
688 public abstract String getPackageCodePath();
692 * @deprecated use {@link #getSharedPreferencesPath(String)}
695 public File getSharedPrefsFile(String name) {
696 return getSharedPreferencesPath(name);
700 * Retrieve and hold the contents of the preferences file 'name', returning
701 * a SharedPreferences through which you can retrieve and modify its
702 * values. Only one instance of the SharedPreferences object is returned
703 * to any callers for the same name, meaning they will see each other's
704 * edits as soon as they are made.
706 * @param name Desired preferences file. If a preferences file by this name
707 * does not exist, it will be created when you retrieve an
708 * editor (SharedPreferences.edit()) and then commit changes (Editor.commit()).
709 * @param mode Operating mode. Use 0 or {@link #MODE_PRIVATE} for the
712 * @return The single {@link SharedPreferences} instance that can be used
713 * to retrieve and modify the preference values.
717 public abstract SharedPreferences getSharedPreferences(String name, int mode);
720 * Retrieve and hold the contents of the preferences file, returning
721 * a SharedPreferences through which you can retrieve and modify its
722 * values. Only one instance of the SharedPreferences object is returned
723 * to any callers for the same name, meaning they will see each other's
724 * edits as soon as they are made.
726 * @param file Desired preferences file. If a preferences file by this name
727 * does not exist, it will be created when you retrieve an
728 * editor (SharedPreferences.edit()) and then commit changes (Editor.commit()).
729 * @param mode Operating mode. Use 0 or {@link #MODE_PRIVATE} for the
732 * @return The single {@link SharedPreferences} instance that can be used
733 * to retrieve and modify the preference values.
735 * @see #getSharedPreferencesPath(String)
739 public abstract SharedPreferences getSharedPreferences(File file, int mode);
742 * Move an existing shared preferences file from the given source storage
743 * context to this context. This is typically used to migrate data between
744 * storage locations after an upgrade, such as moving to device protected
747 * @param sourceContext The source context which contains the existing
748 * shared preferences to move.
749 * @param name The name of the shared preferences file.
750 * @return {@code true} if the move was successful or if the shared
751 * preferences didn't exist in the source context, otherwise
753 * @see #createDeviceProtectedStorageContext()
755 public abstract boolean moveSharedPreferencesFrom(Context sourceContext, String name);
758 * Delete an existing shared preferences file.
760 * @param name The name (unique in the application package) of the shared
762 * @return {@code true} if the shared preferences file was successfully
763 * deleted; else {@code false}.
764 * @see #getSharedPreferences(String, int)
766 public abstract boolean deleteSharedPreferences(String name);
769 * Open a private file associated with this Context's application package
772 * @param name The name of the file to open; can not contain path
775 * @return The resulting {@link FileInputStream}.
777 * @see #openFileOutput
780 * @see java.io.FileInputStream#FileInputStream(String)
782 public abstract FileInputStream openFileInput(String name)
783 throws FileNotFoundException;
786 * Open a private file associated with this Context's application package
787 * for writing. Creates the file if it doesn't already exist.
789 * No additional permissions are required for the calling app to read or
790 * write the returned file.
792 * @param name The name of the file to open; can not contain path
794 * @param mode Operating mode. Use 0 or {@link #MODE_PRIVATE} for the
795 * default operation. Use {@link #MODE_APPEND} to append to an
797 * @return The resulting {@link FileOutputStream}.
800 * @see #openFileInput
803 * @see java.io.FileOutputStream#FileOutputStream(String)
805 public abstract FileOutputStream openFileOutput(String name, int mode)
806 throws FileNotFoundException;
809 * Delete the given private file associated with this Context's
810 * application package.
812 * @param name The name of the file to delete; can not contain path
815 * @return {@code true} if the file was successfully deleted; else
818 * @see #openFileInput
819 * @see #openFileOutput
821 * @see java.io.File#delete()
823 public abstract boolean deleteFile(String name);
826 * Returns the absolute path on the filesystem where a file created with
827 * {@link #openFileOutput} is stored.
829 * The returned path may change over time if the calling app is moved to an
830 * adopted storage device, so only relative paths should be persisted.
832 * @param name The name of the file for which you would like to get
835 * @return An absolute path to the given file.
837 * @see #openFileOutput
841 public abstract File getFileStreamPath(String name);
844 * Returns the absolute path on the filesystem where a file created with
845 * {@link #getSharedPreferences(String, int)} is stored.
847 * The returned path may change over time if the calling app is moved to an
848 * adopted storage device, so only relative paths should be persisted.
850 * @param name The name of the shared preferences for which you would like
852 * @return An absolute path to the given file.
853 * @see #getSharedPreferences(String, int)
856 public abstract File getSharedPreferencesPath(String name);
859 * Returns the absolute path to the directory on the filesystem where all
860 * private files belonging to this app are stored. Apps should not use this
861 * path directly; they should instead use {@link #getFilesDir()},
862 * {@link #getCacheDir()}, {@link #getDir(String, int)}, or other storage
863 * APIs on this class.
865 * The returned path may change over time if the calling app is moved to an
866 * adopted storage device, so only relative paths should be persisted.
868 * No additional permissions are required for the calling app to read or
869 * write files under the returned path.
871 * @see ApplicationInfo#dataDir
873 public abstract File getDataDir();
876 * Returns the absolute path to the directory on the filesystem where files
877 * created with {@link #openFileOutput} are stored.
879 * The returned path may change over time if the calling app is moved to an
880 * adopted storage device, so only relative paths should be persisted.
882 * No additional permissions are required for the calling app to read or
883 * write files under the returned path.
885 * @return The path of the directory holding application files.
886 * @see #openFileOutput
887 * @see #getFileStreamPath
890 public abstract File getFilesDir();
893 * Returns the absolute path to the directory on the filesystem similar to
894 * {@link #getFilesDir()}. The difference is that files placed under this
895 * directory will be excluded from automatic backup to remote storage. See
896 * {@link android.app.backup.BackupAgent BackupAgent} for a full discussion
897 * of the automatic backup mechanism in Android.
899 * The returned path may change over time if the calling app is moved to an
900 * adopted storage device, so only relative paths should be persisted.
902 * No additional permissions are required for the calling app to read or
903 * write files under the returned path.
905 * @return The path of the directory holding application files that will not
906 * be automatically backed up to remote storage.
907 * @see #openFileOutput
908 * @see #getFileStreamPath
910 * @see android.app.backup.BackupAgent
912 public abstract File getNoBackupFilesDir();
915 * Returns the absolute path to the directory on the primary shared/external
916 * storage device where the application can place persistent files it owns.
917 * These files are internal to the applications, and not typically visible
918 * to the user as media.
920 * This is like {@link #getFilesDir()} in that these files will be deleted
921 * when the application is uninstalled, however there are some important
924 * <li>Shared storage may not always be available, since removable media can
925 * be ejected by the user. Media state can be checked using
926 * {@link Environment#getExternalStorageState(File)}.
927 * <li>There is no security enforced with these files. For example, any
928 * application holding
929 * {@link android.Manifest.permission#WRITE_EXTERNAL_STORAGE} can write to
933 * If a shared storage device is emulated (as determined by
934 * {@link Environment#isExternalStorageEmulated(File)}), it's contents are
935 * backed by a private user data partition, which means there is little
936 * benefit to storing data here instead of the private directories returned
937 * by {@link #getFilesDir()}, etc.
939 * Starting in {@link android.os.Build.VERSION_CODES#KITKAT}, no permissions
940 * are required to read or write to the returned path; it's always
941 * accessible to the calling app. This only applies to paths generated for
942 * package name of the calling application. To access paths belonging to
944 * {@link android.Manifest.permission#WRITE_EXTERNAL_STORAGE} and/or
945 * {@link android.Manifest.permission#READ_EXTERNAL_STORAGE} are required.
947 * On devices with multiple users (as described by {@link UserManager}),
948 * each user has their own isolated shared storage. Applications only have
949 * access to the shared storage for the user they're running as.
951 * The returned path may change over time if different shared storage media
952 * is inserted, so only relative paths should be persisted.
954 * Here is an example of typical code to manipulate a file in an
955 * application's shared storage:
957 * {@sample development/samples/ApiDemos/src/com/example/android/apis/content/ExternalStorage.java
960 * If you supply a non-null <var>type</var> to this function, the returned
961 * file will be a path to a sub-directory of the given type. Though these
962 * files are not automatically scanned by the media scanner, you can
963 * explicitly add them to the media database with
964 * {@link android.media.MediaScannerConnection#scanFile(Context, String[], String[], android.media.MediaScannerConnection.OnScanCompletedListener)
965 * MediaScannerConnection.scanFile}. Note that this is not the same as
966 * {@link android.os.Environment#getExternalStoragePublicDirectory
967 * Environment.getExternalStoragePublicDirectory()}, which provides
968 * directories of media shared by all applications. The directories returned
969 * here are owned by the application, and their contents will be removed
970 * when the application is uninstalled. Unlike
971 * {@link android.os.Environment#getExternalStoragePublicDirectory
972 * Environment.getExternalStoragePublicDirectory()}, the directory returned
973 * here will be automatically created for you.
975 * Here is an example of typical code to manipulate a picture in an
976 * application's shared storage and add it to the media database:
978 * {@sample development/samples/ApiDemos/src/com/example/android/apis/content/ExternalStorage.java
981 * @param type The type of files directory to return. May be {@code null}
982 * for the root of the files directory or one of the following
983 * constants for a subdirectory:
984 * {@link android.os.Environment#DIRECTORY_MUSIC},
985 * {@link android.os.Environment#DIRECTORY_PODCASTS},
986 * {@link android.os.Environment#DIRECTORY_RINGTONES},
987 * {@link android.os.Environment#DIRECTORY_ALARMS},
988 * {@link android.os.Environment#DIRECTORY_NOTIFICATIONS},
989 * {@link android.os.Environment#DIRECTORY_PICTURES}, or
990 * {@link android.os.Environment#DIRECTORY_MOVIES}.
991 * @return the absolute path to application-specific directory. May return
992 * {@code null} if shared storage is not currently available.
994 * @see #getExternalFilesDirs(String)
995 * @see Environment#getExternalStorageState(File)
996 * @see Environment#isExternalStorageEmulated(File)
997 * @see Environment#isExternalStorageRemovable(File)
1000 public abstract File getExternalFilesDir(@Nullable String type);
1003 * Returns absolute paths to application-specific directories on all
1004 * shared/external storage devices where the application can place
1005 * persistent files it owns. These files are internal to the application,
1006 * and not typically visible to the user as media.
1008 * This is like {@link #getFilesDir()} in that these files will be deleted
1009 * when the application is uninstalled, however there are some important
1012 * <li>Shared storage may not always be available, since removable media can
1013 * be ejected by the user. Media state can be checked using
1014 * {@link Environment#getExternalStorageState(File)}.
1015 * <li>There is no security enforced with these files. For example, any
1016 * application holding
1017 * {@link android.Manifest.permission#WRITE_EXTERNAL_STORAGE} can write to
1021 * If a shared storage device is emulated (as determined by
1022 * {@link Environment#isExternalStorageEmulated(File)}), it's contents are
1023 * backed by a private user data partition, which means there is little
1024 * benefit to storing data here instead of the private directories returned
1025 * by {@link #getFilesDir()}, etc.
1027 * Shared storage devices returned here are considered a stable part of the
1028 * device, including physical media slots under a protective cover. The
1029 * returned paths do not include transient devices, such as USB flash drives
1030 * connected to handheld devices.
1032 * An application may store data on any or all of the returned devices. For
1033 * example, an app may choose to store large files on the device with the
1034 * most available space, as measured by {@link StatFs}.
1036 * No additional permissions are required for the calling app to read or
1037 * write files under the returned path. Write access outside of these paths
1038 * on secondary external storage devices is not available.
1040 * The returned path may change over time if different shared storage media
1041 * is inserted, so only relative paths should be persisted.
1043 * @param type The type of files directory to return. May be {@code null}
1044 * for the root of the files directory or one of the following
1045 * constants for a subdirectory:
1046 * {@link android.os.Environment#DIRECTORY_MUSIC},
1047 * {@link android.os.Environment#DIRECTORY_PODCASTS},
1048 * {@link android.os.Environment#DIRECTORY_RINGTONES},
1049 * {@link android.os.Environment#DIRECTORY_ALARMS},
1050 * {@link android.os.Environment#DIRECTORY_NOTIFICATIONS},
1051 * {@link android.os.Environment#DIRECTORY_PICTURES}, or
1052 * {@link android.os.Environment#DIRECTORY_MOVIES}.
1053 * @return the absolute paths to application-specific directories. Some
1054 * individual paths may be {@code null} if that shared storage is
1055 * not currently available. The first path returned is the same as
1056 * {@link #getExternalFilesDir(String)}.
1057 * @see #getExternalFilesDir(String)
1058 * @see Environment#getExternalStorageState(File)
1059 * @see Environment#isExternalStorageEmulated(File)
1060 * @see Environment#isExternalStorageRemovable(File)
1062 public abstract File[] getExternalFilesDirs(String type);
1065 * Return the primary shared/external storage directory where this
1066 * application's OBB files (if there are any) can be found. Note if the
1067 * application does not have any OBB files, this directory may not exist.
1069 * This is like {@link #getFilesDir()} in that these files will be deleted
1070 * when the application is uninstalled, however there are some important
1073 * <li>Shared storage may not always be available, since removable media can
1074 * be ejected by the user. Media state can be checked using
1075 * {@link Environment#getExternalStorageState(File)}.
1076 * <li>There is no security enforced with these files. For example, any
1077 * application holding
1078 * {@link android.Manifest.permission#WRITE_EXTERNAL_STORAGE} can write to
1082 * Starting in {@link android.os.Build.VERSION_CODES#KITKAT}, no permissions
1083 * are required to read or write to the returned path; it's always
1084 * accessible to the calling app. This only applies to paths generated for
1085 * package name of the calling application. To access paths belonging to
1087 * {@link android.Manifest.permission#WRITE_EXTERNAL_STORAGE} and/or
1088 * {@link android.Manifest.permission#READ_EXTERNAL_STORAGE} are required.
1090 * On devices with multiple users (as described by {@link UserManager}),
1091 * multiple users may share the same OBB storage location. Applications
1092 * should ensure that multiple instances running under different users don't
1093 * interfere with each other.
1095 * @return the absolute path to application-specific directory. May return
1096 * {@code null} if shared storage is not currently available.
1097 * @see #getObbDirs()
1098 * @see Environment#getExternalStorageState(File)
1099 * @see Environment#isExternalStorageEmulated(File)
1100 * @see Environment#isExternalStorageRemovable(File)
1102 public abstract File getObbDir();
1105 * Returns absolute paths to application-specific directories on all
1106 * shared/external storage devices where the application's OBB files (if
1107 * there are any) can be found. Note if the application does not have any
1108 * OBB files, these directories may not exist.
1110 * This is like {@link #getFilesDir()} in that these files will be deleted
1111 * when the application is uninstalled, however there are some important
1114 * <li>Shared storage may not always be available, since removable media can
1115 * be ejected by the user. Media state can be checked using
1116 * {@link Environment#getExternalStorageState(File)}.
1117 * <li>There is no security enforced with these files. For example, any
1118 * application holding
1119 * {@link android.Manifest.permission#WRITE_EXTERNAL_STORAGE} can write to
1123 * Shared storage devices returned here are considered a stable part of the
1124 * device, including physical media slots under a protective cover. The
1125 * returned paths do not include transient devices, such as USB flash drives
1126 * connected to handheld devices.
1128 * An application may store data on any or all of the returned devices. For
1129 * example, an app may choose to store large files on the device with the
1130 * most available space, as measured by {@link StatFs}.
1132 * No additional permissions are required for the calling app to read or
1133 * write files under the returned path. Write access outside of these paths
1134 * on secondary external storage devices is not available.
1136 * @return the absolute paths to application-specific directories. Some
1137 * individual paths may be {@code null} if that shared storage is
1138 * not currently available. The first path returned is the same as
1139 * {@link #getObbDir()}
1141 * @see Environment#getExternalStorageState(File)
1142 * @see Environment#isExternalStorageEmulated(File)
1143 * @see Environment#isExternalStorageRemovable(File)
1145 public abstract File[] getObbDirs();
1148 * Returns the absolute path to the application specific cache directory on
1149 * the filesystem. These files will be ones that get deleted first when the
1150 * device runs low on storage. There is no guarantee when these files will
1153 * <strong>Note: you should not <em>rely</em> on the system deleting these
1154 * files for you; you should always have a reasonable maximum, such as 1 MB,
1155 * for the amount of space you consume with cache files, and prune those
1156 * files when exceeding that space.</strong> If your app requires a larger
1157 * cache (larger than 1 MB), you should use {@link #getExternalCacheDir()}
1160 * The returned path may change over time if the calling app is moved to an
1161 * adopted storage device, so only relative paths should be persisted.
1163 * Apps require no extra permissions to read or write to the returned path,
1164 * since this path lives in their private storage.
1166 * @return The path of the directory holding application cache files.
1167 * @see #openFileOutput
1168 * @see #getFileStreamPath
1170 * @see #getExternalCacheDir
1172 public abstract File getCacheDir();
1175 * Returns the absolute path to the application specific cache directory on
1176 * the filesystem designed for storing cached code. The system will delete
1177 * any files stored in this location both when your specific application is
1178 * upgraded, and when the entire platform is upgraded.
1180 * This location is optimal for storing compiled or optimized code generated
1181 * by your application at runtime.
1183 * The returned path may change over time if the calling app is moved to an
1184 * adopted storage device, so only relative paths should be persisted.
1186 * Apps require no extra permissions to read or write to the returned path,
1187 * since this path lives in their private storage.
1189 * @return The path of the directory holding application code cache files.
1191 public abstract File getCodeCacheDir();
1194 * Returns absolute path to application-specific directory on the primary
1195 * shared/external storage device where the application can place cache
1196 * files it owns. These files are internal to the application, and not
1197 * typically visible to the user as media.
1199 * This is like {@link #getCacheDir()} in that these files will be deleted
1200 * when the application is uninstalled, however there are some important
1203 * <li>The platform does not always monitor the space available in shared
1204 * storage, and thus may not automatically delete these files. Apps should
1205 * always manage the maximum space used in this location. Currently the only
1206 * time files here will be deleted by the platform is when running on
1207 * {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR1} or later and
1208 * {@link Environment#isExternalStorageEmulated(File)} returns true.
1209 * <li>Shared storage may not always be available, since removable media can
1210 * be ejected by the user. Media state can be checked using
1211 * {@link Environment#getExternalStorageState(File)}.
1212 * <li>There is no security enforced with these files. For example, any
1213 * application holding
1214 * {@link android.Manifest.permission#WRITE_EXTERNAL_STORAGE} can write to
1218 * If a shared storage device is emulated (as determined by
1219 * {@link Environment#isExternalStorageEmulated(File)}), its contents are
1220 * backed by a private user data partition, which means there is little
1221 * benefit to storing data here instead of the private directory returned by
1222 * {@link #getCacheDir()}.
1224 * Starting in {@link android.os.Build.VERSION_CODES#KITKAT}, no permissions
1225 * are required to read or write to the returned path; it's always
1226 * accessible to the calling app. This only applies to paths generated for
1227 * package name of the calling application. To access paths belonging to
1229 * {@link android.Manifest.permission#WRITE_EXTERNAL_STORAGE} and/or
1230 * {@link android.Manifest.permission#READ_EXTERNAL_STORAGE} are required.
1232 * On devices with multiple users (as described by {@link UserManager}),
1233 * each user has their own isolated shared storage. Applications only have
1234 * access to the shared storage for the user they're running as.
1236 * The returned path may change over time if different shared storage media
1237 * is inserted, so only relative paths should be persisted.
1239 * @return the absolute path to application-specific directory. May return
1240 * {@code null} if shared storage is not currently available.
1242 * @see #getExternalCacheDirs()
1243 * @see Environment#getExternalStorageState(File)
1244 * @see Environment#isExternalStorageEmulated(File)
1245 * @see Environment#isExternalStorageRemovable(File)
1248 public abstract File getExternalCacheDir();
1251 * Returns absolute path to application-specific directory in the preloaded cache.
1252 * <p>Files stored in the cache directory can be deleted when the device runs low on storage.
1253 * There is no guarantee when these files will be deleted.
1258 public abstract File getPreloadsFileCache();
1261 * Returns absolute paths to application-specific directories on all
1262 * shared/external storage devices where the application can place cache
1263 * files it owns. These files are internal to the application, and not
1264 * typically visible to the user as media.
1266 * This is like {@link #getCacheDir()} in that these files will be deleted
1267 * when the application is uninstalled, however there are some important
1270 * <li>The platform does not always monitor the space available in shared
1271 * storage, and thus may not automatically delete these files. Apps should
1272 * always manage the maximum space used in this location. Currently the only
1273 * time files here will be deleted by the platform is when running on
1274 * {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR1} or later and
1275 * {@link Environment#isExternalStorageEmulated(File)} returns true.
1276 * <li>Shared storage may not always be available, since removable media can
1277 * be ejected by the user. Media state can be checked using
1278 * {@link Environment#getExternalStorageState(File)}.
1279 * <li>There is no security enforced with these files. For example, any
1280 * application holding
1281 * {@link android.Manifest.permission#WRITE_EXTERNAL_STORAGE} can write to
1285 * If a shared storage device is emulated (as determined by
1286 * {@link Environment#isExternalStorageEmulated(File)}), it's contents are
1287 * backed by a private user data partition, which means there is little
1288 * benefit to storing data here instead of the private directory returned by
1289 * {@link #getCacheDir()}.
1291 * Shared storage devices returned here are considered a stable part of the
1292 * device, including physical media slots under a protective cover. The
1293 * returned paths do not include transient devices, such as USB flash drives
1294 * connected to handheld devices.
1296 * An application may store data on any or all of the returned devices. For
1297 * example, an app may choose to store large files on the device with the
1298 * most available space, as measured by {@link StatFs}.
1300 * No additional permissions are required for the calling app to read or
1301 * write files under the returned path. Write access outside of these paths
1302 * on secondary external storage devices is not available.
1304 * The returned paths may change over time if different shared storage media
1305 * is inserted, so only relative paths should be persisted.
1307 * @return the absolute paths to application-specific directories. Some
1308 * individual paths may be {@code null} if that shared storage is
1309 * not currently available. The first path returned is the same as
1310 * {@link #getExternalCacheDir()}.
1311 * @see #getExternalCacheDir()
1312 * @see Environment#getExternalStorageState(File)
1313 * @see Environment#isExternalStorageEmulated(File)
1314 * @see Environment#isExternalStorageRemovable(File)
1316 public abstract File[] getExternalCacheDirs();
1319 * Returns absolute paths to application-specific directories on all
1320 * shared/external storage devices where the application can place media
1321 * files. These files are scanned and made available to other apps through
1322 * {@link MediaStore}.
1324 * This is like {@link #getExternalFilesDirs} in that these files will be
1325 * deleted when the application is uninstalled, however there are some
1326 * important differences:
1328 * <li>Shared storage may not always be available, since removable media can
1329 * be ejected by the user. Media state can be checked using
1330 * {@link Environment#getExternalStorageState(File)}.
1331 * <li>There is no security enforced with these files. For example, any
1332 * application holding
1333 * {@link android.Manifest.permission#WRITE_EXTERNAL_STORAGE} can write to
1337 * Shared storage devices returned here are considered a stable part of the
1338 * device, including physical media slots under a protective cover. The
1339 * returned paths do not include transient devices, such as USB flash drives
1340 * connected to handheld devices.
1342 * An application may store data on any or all of the returned devices. For
1343 * example, an app may choose to store large files on the device with the
1344 * most available space, as measured by {@link StatFs}.
1346 * No additional permissions are required for the calling app to read or
1347 * write files under the returned path. Write access outside of these paths
1348 * on secondary external storage devices is not available.
1350 * The returned paths may change over time if different shared storage media
1351 * is inserted, so only relative paths should be persisted.
1353 * @return the absolute paths to application-specific directories. Some
1354 * individual paths may be {@code null} if that shared storage is
1355 * not currently available.
1356 * @see Environment#getExternalStorageState(File)
1357 * @see Environment#isExternalStorageEmulated(File)
1358 * @see Environment#isExternalStorageRemovable(File)
1360 public abstract File[] getExternalMediaDirs();
1363 * Returns an array of strings naming the private files associated with
1364 * this Context's application package.
1366 * @return Array of strings naming the private files.
1368 * @see #openFileInput
1369 * @see #openFileOutput
1372 public abstract String[] fileList();
1375 * Retrieve, creating if needed, a new directory in which the application
1376 * can place its own custom data files. You can use the returned File
1377 * object to create and access files in this directory. Note that files
1378 * created through a File object will only be accessible by your own
1379 * application; you can only set the mode of the entire directory, not
1380 * of individual files.
1382 * The returned path may change over time if the calling app is moved to an
1383 * adopted storage device, so only relative paths should be persisted.
1385 * Apps require no extra permissions to read or write to the returned path,
1386 * since this path lives in their private storage.
1388 * @param name Name of the directory to retrieve. This is a directory
1389 * that is created as part of your application data.
1390 * @param mode Operating mode. Use 0 or {@link #MODE_PRIVATE} for the
1391 * default operation.
1393 * @return A {@link File} object for the requested directory. The directory
1394 * will have been created if it does not already exist.
1396 * @see #openFileOutput(String, int)
1398 public abstract File getDir(String name, int mode);
1401 * Open a new private SQLiteDatabase associated with this Context's
1402 * application package. Create the database file if it doesn't exist.
1404 * @param name The name (unique in the application package) of the database.
1405 * @param mode Operating mode. Use 0 or {@link #MODE_PRIVATE} for the
1406 * default operation. Use
1407 * {@link #MODE_ENABLE_WRITE_AHEAD_LOGGING} to enable write-ahead
1408 * logging by default. Use {@link #MODE_NO_LOCALIZED_COLLATORS}
1409 * to disable localized collators.
1410 * @param factory An optional factory class that is called to instantiate a
1411 * cursor when query is called.
1412 * @return The contents of a newly created database with the given name.
1413 * @throws android.database.sqlite.SQLiteException if the database file
1414 * could not be opened.
1415 * @see #MODE_PRIVATE
1416 * @see #MODE_ENABLE_WRITE_AHEAD_LOGGING
1417 * @see #MODE_NO_LOCALIZED_COLLATORS
1418 * @see #deleteDatabase
1420 public abstract SQLiteDatabase openOrCreateDatabase(String name,
1421 int mode, CursorFactory factory);
1424 * Open a new private SQLiteDatabase associated with this Context's
1425 * application package. Creates the database file if it doesn't exist.
1427 * Accepts input param: a concrete instance of {@link DatabaseErrorHandler}
1428 * to be used to handle corruption when sqlite reports database corruption.
1431 * @param name The name (unique in the application package) of the database.
1432 * @param mode Operating mode. Use 0 or {@link #MODE_PRIVATE} for the
1433 * default operation. Use
1434 * {@link #MODE_ENABLE_WRITE_AHEAD_LOGGING} to enable write-ahead
1435 * logging by default. Use {@link #MODE_NO_LOCALIZED_COLLATORS}
1436 * to disable localized collators.
1437 * @param factory An optional factory class that is called to instantiate a
1438 * cursor when query is called.
1439 * @param errorHandler the {@link DatabaseErrorHandler} to be used when
1440 * sqlite reports database corruption. if null,
1441 * {@link android.database.DefaultDatabaseErrorHandler} is
1443 * @return The contents of a newly created database with the given name.
1444 * @throws android.database.sqlite.SQLiteException if the database file
1445 * could not be opened.
1446 * @see #MODE_PRIVATE
1447 * @see #MODE_ENABLE_WRITE_AHEAD_LOGGING
1448 * @see #MODE_NO_LOCALIZED_COLLATORS
1449 * @see #deleteDatabase
1451 public abstract SQLiteDatabase openOrCreateDatabase(String name,
1452 int mode, CursorFactory factory,
1453 @Nullable DatabaseErrorHandler errorHandler);
1456 * Move an existing database file from the given source storage context to
1457 * this context. This is typically used to migrate data between storage
1458 * locations after an upgrade, such as migrating to device protected
1461 * The database must be closed before being moved.
1463 * @param sourceContext The source context which contains the existing
1465 * @param name The name of the database file.
1466 * @return {@code true} if the move was successful or if the database didn't
1467 * exist in the source context, otherwise {@code false}.
1468 * @see #createDeviceProtectedStorageContext()
1470 public abstract boolean moveDatabaseFrom(Context sourceContext, String name);
1473 * Delete an existing private SQLiteDatabase associated with this Context's
1474 * application package.
1476 * @param name The name (unique in the application package) of the
1479 * @return {@code true} if the database was successfully deleted; else {@code false}.
1481 * @see #openOrCreateDatabase
1483 public abstract boolean deleteDatabase(String name);
1486 * Returns the absolute path on the filesystem where a database created with
1487 * {@link #openOrCreateDatabase} is stored.
1489 * The returned path may change over time if the calling app is moved to an
1490 * adopted storage device, so only relative paths should be persisted.
1492 * @param name The name of the database for which you would like to get
1495 * @return An absolute path to the given database.
1497 * @see #openOrCreateDatabase
1499 public abstract File getDatabasePath(String name);
1502 * Returns an array of strings naming the private databases associated with
1503 * this Context's application package.
1505 * @return Array of strings naming the private databases.
1507 * @see #openOrCreateDatabase
1508 * @see #deleteDatabase
1510 public abstract String[] databaseList();
1513 * @deprecated Use {@link android.app.WallpaperManager#getDrawable
1514 * WallpaperManager.get()} instead.
1517 public abstract Drawable getWallpaper();
1520 * @deprecated Use {@link android.app.WallpaperManager#peekDrawable
1521 * WallpaperManager.peek()} instead.
1524 public abstract Drawable peekWallpaper();
1527 * @deprecated Use {@link android.app.WallpaperManager#getDesiredMinimumWidth()
1528 * WallpaperManager.getDesiredMinimumWidth()} instead.
1531 public abstract int getWallpaperDesiredMinimumWidth();
1534 * @deprecated Use {@link android.app.WallpaperManager#getDesiredMinimumHeight()
1535 * WallpaperManager.getDesiredMinimumHeight()} instead.
1538 public abstract int getWallpaperDesiredMinimumHeight();
1541 * @deprecated Use {@link android.app.WallpaperManager#setBitmap(Bitmap)
1542 * WallpaperManager.set()} instead.
1543 * <p>This method requires the caller to hold the permission
1544 * {@link android.Manifest.permission#SET_WALLPAPER}.
1547 public abstract void setWallpaper(Bitmap bitmap) throws IOException;
1550 * @deprecated Use {@link android.app.WallpaperManager#setStream(InputStream)
1551 * WallpaperManager.set()} instead.
1552 * <p>This method requires the caller to hold the permission
1553 * {@link android.Manifest.permission#SET_WALLPAPER}.
1556 public abstract void setWallpaper(InputStream data) throws IOException;
1559 * @deprecated Use {@link android.app.WallpaperManager#clear
1560 * WallpaperManager.clear()} instead.
1561 * <p>This method requires the caller to hold the permission
1562 * {@link android.Manifest.permission#SET_WALLPAPER}.
1565 public abstract void clearWallpaper() throws IOException;
1568 * Same as {@link #startActivity(Intent, Bundle)} with no options
1571 * @param intent The description of the activity to start.
1573 * @throws ActivityNotFoundException
1575 * @see #startActivity(Intent, Bundle)
1576 * @see PackageManager#resolveActivity
1578 public abstract void startActivity(@RequiresPermission Intent intent);
1581 * Version of {@link #startActivity(Intent)} that allows you to specify the
1582 * user the activity will be started for. This is not available to applications
1583 * that are not pre-installed on the system image. Using it requires holding
1584 * the INTERACT_ACROSS_USERS_FULL permission.
1585 * @param intent The description of the activity to start.
1586 * @param user The UserHandle of the user to start this activity for.
1587 * @throws ActivityNotFoundException
1590 public void startActivityAsUser(@RequiresPermission Intent intent, UserHandle user) {
1591 throw new RuntimeException("Not implemented. Must override in a subclass.");
1595 * Launch a new activity. You will not receive any information about when
1596 * the activity exits.
1598 * <p>Note that if this method is being called from outside of an
1599 * {@link android.app.Activity} Context, then the Intent must include
1600 * the {@link Intent#FLAG_ACTIVITY_NEW_TASK} launch flag. This is because,
1601 * without being started from an existing Activity, there is no existing
1602 * task in which to place the new activity and thus it needs to be placed
1603 * in its own separate task.
1605 * <p>This method throws {@link ActivityNotFoundException}
1606 * if there was no Activity found to run the given Intent.
1608 * @param intent The description of the activity to start.
1609 * @param options Additional options for how the Activity should be started.
1610 * May be null if there are no options. See {@link android.app.ActivityOptions}
1611 * for how to build the Bundle supplied here; there are no supported definitions
1612 * for building it manually.
1614 * @throws ActivityNotFoundException
1616 * @see #startActivity(Intent)
1617 * @see PackageManager#resolveActivity
1619 public abstract void startActivity(@RequiresPermission Intent intent,
1620 @Nullable Bundle options);
1623 * Version of {@link #startActivity(Intent, Bundle)} that allows you to specify the
1624 * user the activity will be started for. This is not available to applications
1625 * that are not pre-installed on the system image. Using it requires holding
1626 * the INTERACT_ACROSS_USERS_FULL permission.
1627 * @param intent The description of the activity to start.
1628 * @param options Additional options for how the Activity should be started.
1629 * May be null if there are no options. See {@link android.app.ActivityOptions}
1630 * for how to build the Bundle supplied here; there are no supported definitions
1631 * for building it manually.
1632 * @param userId The UserHandle of the user to start this activity for.
1633 * @throws ActivityNotFoundException
1636 public void startActivityAsUser(@RequiresPermission Intent intent, @Nullable Bundle options,
1637 UserHandle userId) {
1638 throw new RuntimeException("Not implemented. Must override in a subclass.");
1642 * Version of {@link #startActivity(Intent, Bundle)} that returns a result to the caller. This
1643 * is only supported for Views and Fragments.
1644 * @param who The identifier for the calling element that will receive the result.
1645 * @param intent The intent to start.
1646 * @param requestCode The code that will be returned with onActivityResult() identifying this
1648 * @param options Additional options for how the Activity should be started.
1649 * May be null if there are no options. See {@link android.app.ActivityOptions}
1650 * for how to build the Bundle supplied here; there are no supported definitions
1651 * for building it manually.
1654 public void startActivityForResult(
1655 @NonNull String who, Intent intent, int requestCode, @Nullable Bundle options) {
1656 throw new RuntimeException("This method is only implemented for Activity-based Contexts. "
1657 + "Check canStartActivityForResult() before calling.");
1661 * Identifies whether this Context instance will be able to process calls to
1662 * {@link #startActivityForResult(String, Intent, int, Bundle)}.
1665 public boolean canStartActivityForResult() {
1670 * Same as {@link #startActivities(Intent[], Bundle)} with no options
1673 * @param intents An array of Intents to be started.
1675 * @throws ActivityNotFoundException
1677 * @see #startActivities(Intent[], Bundle)
1678 * @see PackageManager#resolveActivity
1680 public abstract void startActivities(@RequiresPermission Intent[] intents);
1683 * Launch multiple new activities. This is generally the same as calling
1684 * {@link #startActivity(Intent)} for the first Intent in the array,
1685 * that activity during its creation calling {@link #startActivity(Intent)}
1686 * for the second entry, etc. Note that unlike that approach, generally
1687 * none of the activities except the last in the array will be created
1688 * at this point, but rather will be created when the user first visits
1689 * them (due to pressing back from the activity on top).
1691 * <p>This method throws {@link ActivityNotFoundException}
1692 * if there was no Activity found for <em>any</em> given Intent. In this
1693 * case the state of the activity stack is undefined (some Intents in the
1694 * list may be on it, some not), so you probably want to avoid such situations.
1696 * @param intents An array of Intents to be started.
1697 * @param options Additional options for how the Activity should be started.
1698 * See {@link android.content.Context#startActivity(Intent, Bundle)}
1699 * Context.startActivity(Intent, Bundle)} for more details.
1701 * @throws ActivityNotFoundException
1703 * @see #startActivities(Intent[])
1704 * @see PackageManager#resolveActivity
1706 public abstract void startActivities(@RequiresPermission Intent[] intents, Bundle options);
1710 * Launch multiple new activities. This is generally the same as calling
1711 * {@link #startActivity(Intent)} for the first Intent in the array,
1712 * that activity during its creation calling {@link #startActivity(Intent)}
1713 * for the second entry, etc. Note that unlike that approach, generally
1714 * none of the activities except the last in the array will be created
1715 * at this point, but rather will be created when the user first visits
1716 * them (due to pressing back from the activity on top).
1718 * <p>This method throws {@link ActivityNotFoundException}
1719 * if there was no Activity found for <em>any</em> given Intent. In this
1720 * case the state of the activity stack is undefined (some Intents in the
1721 * list may be on it, some not), so you probably want to avoid such situations.
1723 * @param intents An array of Intents to be started.
1724 * @param options Additional options for how the Activity should be started.
1725 * @param userHandle The user for whom to launch the activities
1726 * See {@link android.content.Context#startActivity(Intent, Bundle)}
1727 * Context.startActivity(Intent, Bundle)} for more details.
1729 * @throws ActivityNotFoundException
1731 * @see #startActivities(Intent[])
1732 * @see PackageManager#resolveActivity
1734 public void startActivitiesAsUser(Intent[] intents, Bundle options, UserHandle userHandle) {
1735 throw new RuntimeException("Not implemented. Must override in a subclass.");
1739 * Same as {@link #startIntentSender(IntentSender, Intent, int, int, int, Bundle)}
1740 * with no options specified.
1742 * @param intent The IntentSender to launch.
1743 * @param fillInIntent If non-null, this will be provided as the
1744 * intent parameter to {@link IntentSender#sendIntent}.
1745 * @param flagsMask Intent flags in the original IntentSender that you
1746 * would like to change.
1747 * @param flagsValues Desired values for any bits set in
1748 * <var>flagsMask</var>
1749 * @param extraFlags Always set to 0.
1751 * @see #startActivity(Intent)
1752 * @see #startIntentSender(IntentSender, Intent, int, int, int, Bundle)
1754 public abstract void startIntentSender(IntentSender intent,
1755 Intent fillInIntent, int flagsMask, int flagsValues, int extraFlags)
1756 throws IntentSender.SendIntentException;
1759 * Like {@link #startActivity(Intent, Bundle)}, but taking a IntentSender
1760 * to start. If the IntentSender is for an activity, that activity will be started
1761 * as if you had called the regular {@link #startActivity(Intent)}
1762 * here; otherwise, its associated action will be executed (such as
1763 * sending a broadcast) as if you had called
1764 * {@link IntentSender#sendIntent IntentSender.sendIntent} on it.
1766 * @param intent The IntentSender to launch.
1767 * @param fillInIntent If non-null, this will be provided as the
1768 * intent parameter to {@link IntentSender#sendIntent}.
1769 * @param flagsMask Intent flags in the original IntentSender that you
1770 * would like to change.
1771 * @param flagsValues Desired values for any bits set in
1772 * <var>flagsMask</var>
1773 * @param extraFlags Always set to 0.
1774 * @param options Additional options for how the Activity should be started.
1775 * See {@link android.content.Context#startActivity(Intent, Bundle)}
1776 * Context.startActivity(Intent, Bundle)} for more details. If options
1777 * have also been supplied by the IntentSender, options given here will
1778 * override any that conflict with those given by the IntentSender.
1780 * @see #startActivity(Intent, Bundle)
1781 * @see #startIntentSender(IntentSender, Intent, int, int, int)
1783 public abstract void startIntentSender(IntentSender intent,
1784 @Nullable Intent fillInIntent, int flagsMask, int flagsValues, int extraFlags,
1785 Bundle options) throws IntentSender.SendIntentException;
1788 * Broadcast the given intent to all interested BroadcastReceivers. This
1789 * call is asynchronous; it returns immediately, and you will continue
1790 * executing while the receivers are run. No results are propagated from
1791 * receivers and receivers can not abort the broadcast. If you want
1792 * to allow receivers to propagate results or abort the broadcast, you must
1793 * send an ordered broadcast using
1794 * {@link #sendOrderedBroadcast(Intent, String)}.
1796 * <p>See {@link BroadcastReceiver} for more information on Intent broadcasts.
1798 * @param intent The Intent to broadcast; all receivers matching this
1799 * Intent will receive the broadcast.
1801 * @see android.content.BroadcastReceiver
1802 * @see #registerReceiver
1803 * @see #sendBroadcast(Intent, String)
1804 * @see #sendOrderedBroadcast(Intent, String)
1805 * @see #sendOrderedBroadcast(Intent, String, BroadcastReceiver, Handler, int, String, Bundle)
1807 public abstract void sendBroadcast(@RequiresPermission Intent intent);
1810 * Broadcast the given intent to all interested BroadcastReceivers, allowing
1811 * an optional required permission to be enforced. This
1812 * call is asynchronous; it returns immediately, and you will continue
1813 * executing while the receivers are run. No results are propagated from
1814 * receivers and receivers can not abort the broadcast. If you want
1815 * to allow receivers to propagate results or abort the broadcast, you must
1816 * send an ordered broadcast using
1817 * {@link #sendOrderedBroadcast(Intent, String)}.
1819 * <p>See {@link BroadcastReceiver} for more information on Intent broadcasts.
1821 * @param intent The Intent to broadcast; all receivers matching this
1822 * Intent will receive the broadcast.
1823 * @param receiverPermission (optional) String naming a permission that
1824 * a receiver must hold in order to receive your broadcast.
1825 * If null, no permission is required.
1827 * @see android.content.BroadcastReceiver
1828 * @see #registerReceiver
1829 * @see #sendBroadcast(Intent)
1830 * @see #sendOrderedBroadcast(Intent, String)
1831 * @see #sendOrderedBroadcast(Intent, String, BroadcastReceiver, Handler, int, String, Bundle)
1833 public abstract void sendBroadcast(@RequiresPermission Intent intent,
1834 @Nullable String receiverPermission);
1838 * Broadcast the given intent to all interested BroadcastReceivers, allowing
1839 * an array of required permissions to be enforced. This call is asynchronous; it returns
1840 * immediately, and you will continue executing while the receivers are run. No results are
1841 * propagated from receivers and receivers can not abort the broadcast. If you want to allow
1842 * receivers to propagate results or abort the broadcast, you must send an ordered broadcast
1843 * using {@link #sendOrderedBroadcast(Intent, String)}.
1845 * <p>See {@link BroadcastReceiver} for more information on Intent broadcasts.
1847 * @param intent The Intent to broadcast; all receivers matching this
1848 * Intent will receive the broadcast.
1849 * @param receiverPermissions Array of names of permissions that a receiver must hold
1850 * in order to receive your broadcast.
1851 * If null or empty, no permissions are required.
1853 * @see android.content.BroadcastReceiver
1854 * @see #registerReceiver
1855 * @see #sendBroadcast(Intent)
1856 * @see #sendOrderedBroadcast(Intent, String)
1857 * @see #sendOrderedBroadcast(Intent, String, BroadcastReceiver, Handler, int, String, Bundle)
1860 public abstract void sendBroadcastMultiplePermissions(Intent intent,
1861 String[] receiverPermissions);
1864 * Broadcast the given intent to all interested BroadcastReceivers, allowing
1865 * an optional required permission to be enforced. This
1866 * call is asynchronous; it returns immediately, and you will continue
1867 * executing while the receivers are run. No results are propagated from
1868 * receivers and receivers can not abort the broadcast. If you want
1869 * to allow receivers to propagate results or abort the broadcast, you must
1870 * send an ordered broadcast using
1871 * {@link #sendOrderedBroadcast(Intent, String)}.
1873 * <p>See {@link BroadcastReceiver} for more information on Intent broadcasts.
1875 * @param intent The Intent to broadcast; all receivers matching this
1876 * Intent will receive the broadcast.
1877 * @param receiverPermission (optional) String naming a permission that
1878 * a receiver must hold in order to receive your broadcast.
1879 * If null, no permission is required.
1880 * @param options (optional) Additional sending options, generated from a
1881 * {@link android.app.BroadcastOptions}.
1883 * @see android.content.BroadcastReceiver
1884 * @see #registerReceiver
1885 * @see #sendBroadcast(Intent)
1886 * @see #sendOrderedBroadcast(Intent, String)
1887 * @see #sendOrderedBroadcast(Intent, String, BroadcastReceiver, Handler, int, String, Bundle)
1891 public abstract void sendBroadcast(Intent intent,
1892 @Nullable String receiverPermission,
1893 @Nullable Bundle options);
1896 * Like {@link #sendBroadcast(Intent, String)}, but also allows specification
1897 * of an associated app op as per {@link android.app.AppOpsManager}.
1900 public abstract void sendBroadcast(Intent intent,
1901 String receiverPermission, int appOp);
1904 * Broadcast the given intent to all interested BroadcastReceivers, delivering
1905 * them one at a time to allow more preferred receivers to consume the
1906 * broadcast before it is delivered to less preferred receivers. This
1907 * call is asynchronous; it returns immediately, and you will continue
1908 * executing while the receivers are run.
1910 * <p>See {@link BroadcastReceiver} for more information on Intent broadcasts.
1912 * @param intent The Intent to broadcast; all receivers matching this
1913 * Intent will receive the broadcast.
1914 * @param receiverPermission (optional) String naming a permissions that
1915 * a receiver must hold in order to receive your broadcast.
1916 * If null, no permission is required.
1918 * @see android.content.BroadcastReceiver
1919 * @see #registerReceiver
1920 * @see #sendBroadcast(Intent)
1921 * @see #sendOrderedBroadcast(Intent, String, BroadcastReceiver, Handler, int, String, Bundle)
1923 public abstract void sendOrderedBroadcast(@RequiresPermission Intent intent,
1924 @Nullable String receiverPermission);
1927 * Version of {@link #sendBroadcast(Intent)} that allows you to
1928 * receive data back from the broadcast. This is accomplished by
1929 * supplying your own BroadcastReceiver when calling, which will be
1930 * treated as a final receiver at the end of the broadcast -- its
1931 * {@link BroadcastReceiver#onReceive} method will be called with
1932 * the result values collected from the other receivers. The broadcast will
1933 * be serialized in the same way as calling
1934 * {@link #sendOrderedBroadcast(Intent, String)}.
1936 * <p>Like {@link #sendBroadcast(Intent)}, this method is
1937 * asynchronous; it will return before
1938 * resultReceiver.onReceive() is called.
1940 * <p>See {@link BroadcastReceiver} for more information on Intent broadcasts.
1942 * @param intent The Intent to broadcast; all receivers matching this
1943 * Intent will receive the broadcast.
1944 * @param receiverPermission String naming a permissions that
1945 * a receiver must hold in order to receive your broadcast.
1946 * If null, no permission is required.
1947 * @param resultReceiver Your own BroadcastReceiver to treat as the final
1948 * receiver of the broadcast.
1949 * @param scheduler A custom Handler with which to schedule the
1950 * resultReceiver callback; if null it will be
1951 * scheduled in the Context's main thread.
1952 * @param initialCode An initial value for the result code. Often
1953 * Activity.RESULT_OK.
1954 * @param initialData An initial value for the result data. Often
1956 * @param initialExtras An initial value for the result extras. Often
1959 * @see #sendBroadcast(Intent)
1960 * @see #sendBroadcast(Intent, String)
1961 * @see #sendOrderedBroadcast(Intent, String)
1962 * @see android.content.BroadcastReceiver
1963 * @see #registerReceiver
1964 * @see android.app.Activity#RESULT_OK
1966 public abstract void sendOrderedBroadcast(@RequiresPermission @NonNull Intent intent,
1967 @Nullable String receiverPermission, @Nullable BroadcastReceiver resultReceiver,
1968 @Nullable Handler scheduler, int initialCode, @Nullable String initialData,
1969 @Nullable Bundle initialExtras);
1972 * Version of {@link #sendBroadcast(Intent)} that allows you to
1973 * receive data back from the broadcast. This is accomplished by
1974 * supplying your own BroadcastReceiver when calling, which will be
1975 * treated as a final receiver at the end of the broadcast -- its
1976 * {@link BroadcastReceiver#onReceive} method will be called with
1977 * the result values collected from the other receivers. The broadcast will
1978 * be serialized in the same way as calling
1979 * {@link #sendOrderedBroadcast(Intent, String)}.
1981 * <p>Like {@link #sendBroadcast(Intent)}, this method is
1982 * asynchronous; it will return before
1983 * resultReceiver.onReceive() is called.
1985 * <p>See {@link BroadcastReceiver} for more information on Intent broadcasts.
1988 * @param intent The Intent to broadcast; all receivers matching this
1989 * Intent will receive the broadcast.
1990 * @param receiverPermission String naming a permissions that
1991 * a receiver must hold in order to receive your broadcast.
1992 * If null, no permission is required.
1993 * @param options (optional) Additional sending options, generated from a
1994 * {@link android.app.BroadcastOptions}.
1995 * @param resultReceiver Your own BroadcastReceiver to treat as the final
1996 * receiver of the broadcast.
1997 * @param scheduler A custom Handler with which to schedule the
1998 * resultReceiver callback; if null it will be
1999 * scheduled in the Context's main thread.
2000 * @param initialCode An initial value for the result code. Often
2001 * Activity.RESULT_OK.
2002 * @param initialData An initial value for the result data. Often
2004 * @param initialExtras An initial value for the result extras. Often
2006 * @see #sendBroadcast(Intent)
2007 * @see #sendBroadcast(Intent, String)
2008 * @see #sendOrderedBroadcast(Intent, String)
2009 * @see android.content.BroadcastReceiver
2010 * @see #registerReceiver
2011 * @see android.app.Activity#RESULT_OK
2015 public abstract void sendOrderedBroadcast(@NonNull Intent intent,
2016 @Nullable String receiverPermission, @Nullable Bundle options,
2017 @Nullable BroadcastReceiver resultReceiver, @Nullable Handler scheduler,
2018 int initialCode, @Nullable String initialData, @Nullable Bundle initialExtras);
2021 * Like {@link #sendOrderedBroadcast(Intent, String, BroadcastReceiver, android.os.Handler,
2022 * int, String, android.os.Bundle)}, but also allows specification
2023 * of an associated app op as per {@link android.app.AppOpsManager}.
2026 public abstract void sendOrderedBroadcast(Intent intent,
2027 String receiverPermission, int appOp, BroadcastReceiver resultReceiver,
2028 Handler scheduler, int initialCode, String initialData,
2029 Bundle initialExtras);
2032 * Version of {@link #sendBroadcast(Intent)} that allows you to specify the
2033 * user the broadcast will be sent to. This is not available to applications
2034 * that are not pre-installed on the system image. Using it requires holding
2035 * the INTERACT_ACROSS_USERS permission.
2036 * @param intent The intent to broadcast
2037 * @param user UserHandle to send the intent to.
2038 * @see #sendBroadcast(Intent)
2040 public abstract void sendBroadcastAsUser(@RequiresPermission Intent intent,
2044 * Version of {@link #sendBroadcast(Intent, String)} that allows you to specify the
2045 * user the broadcast will be sent to. This is not available to applications
2046 * that are not pre-installed on the system image. Using it requires holding
2047 * the INTERACT_ACROSS_USERS permission.
2049 * @param intent The Intent to broadcast; all receivers matching this
2050 * Intent will receive the broadcast.
2051 * @param user UserHandle to send the intent to.
2052 * @param receiverPermission (optional) String naming a permission that
2053 * a receiver must hold in order to receive your broadcast.
2054 * If null, no permission is required.
2056 * @see #sendBroadcast(Intent, String)
2058 public abstract void sendBroadcastAsUser(@RequiresPermission Intent intent,
2059 UserHandle user, @Nullable String receiverPermission);
2062 * Version of {@link #sendBroadcast(Intent, String, Bundle)} that allows you to specify the
2063 * user the broadcast will be sent to. This is not available to applications
2064 * that are not pre-installed on the system image. Using it requires holding
2065 * the INTERACT_ACROSS_USERS permission.
2067 * @param intent The Intent to broadcast; all receivers matching this
2068 * Intent will receive the broadcast.
2069 * @param user UserHandle to send the intent to.
2070 * @param receiverPermission (optional) String naming a permission that
2071 * a receiver must hold in order to receive your broadcast.
2072 * If null, no permission is required.
2073 * @param options (optional) Additional sending options, generated from a
2074 * {@link android.app.BroadcastOptions}.
2076 * @see #sendBroadcast(Intent, String, Bundle)
2080 public abstract void sendBroadcastAsUser(@RequiresPermission Intent intent,
2081 UserHandle user, @Nullable String receiverPermission, @Nullable Bundle options);
2084 * Version of {@link #sendBroadcast(Intent, String)} that allows you to specify the
2085 * user the broadcast will be sent to. This is not available to applications
2086 * that are not pre-installed on the system image. Using it requires holding
2087 * the INTERACT_ACROSS_USERS permission.
2089 * @param intent The Intent to broadcast; all receivers matching this
2090 * Intent will receive the broadcast.
2091 * @param user UserHandle to send the intent to.
2092 * @param receiverPermission (optional) String naming a permission that
2093 * a receiver must hold in order to receive your broadcast.
2094 * If null, no permission is required.
2095 * @param appOp The app op associated with the broadcast.
2097 * @see #sendBroadcast(Intent, String)
2101 public abstract void sendBroadcastAsUser(@RequiresPermission Intent intent,
2102 UserHandle user, @Nullable String receiverPermission, int appOp);
2106 * {@link #sendOrderedBroadcast(Intent, String, BroadcastReceiver, Handler, int, String, Bundle)}
2107 * that allows you to specify the
2108 * user the broadcast will be sent to. This is not available to applications
2109 * that are not pre-installed on the system image. Using it requires holding
2110 * the INTERACT_ACROSS_USERS permission.
2112 * <p>See {@link BroadcastReceiver} for more information on Intent broadcasts.
2114 * @param intent The Intent to broadcast; all receivers matching this
2115 * Intent will receive the broadcast.
2116 * @param user UserHandle to send the intent to.
2117 * @param receiverPermission String naming a permissions that
2118 * a receiver must hold in order to receive your broadcast.
2119 * If null, no permission is required.
2120 * @param resultReceiver Your own BroadcastReceiver to treat as the final
2121 * receiver of the broadcast.
2122 * @param scheduler A custom Handler with which to schedule the
2123 * resultReceiver callback; if null it will be
2124 * scheduled in the Context's main thread.
2125 * @param initialCode An initial value for the result code. Often
2126 * Activity.RESULT_OK.
2127 * @param initialData An initial value for the result data. Often
2129 * @param initialExtras An initial value for the result extras. Often
2132 * @see #sendOrderedBroadcast(Intent, String, BroadcastReceiver, Handler, int, String, Bundle)
2134 public abstract void sendOrderedBroadcastAsUser(@RequiresPermission Intent intent,
2135 UserHandle user, @Nullable String receiverPermission, BroadcastReceiver resultReceiver,
2136 @Nullable Handler scheduler, int initialCode, @Nullable String initialData,
2137 @Nullable Bundle initialExtras);
2140 * Similar to above but takes an appOp as well, to enforce restrictions.
2141 * @see #sendOrderedBroadcastAsUser(Intent, UserHandle, String,
2142 * BroadcastReceiver, Handler, int, String, Bundle)
2145 public abstract void sendOrderedBroadcastAsUser(Intent intent, UserHandle user,
2146 @Nullable String receiverPermission, int appOp, BroadcastReceiver resultReceiver,
2147 @Nullable Handler scheduler, int initialCode, @Nullable String initialData,
2148 @Nullable Bundle initialExtras);
2151 * Similar to above but takes an appOp as well, to enforce restrictions, and an options Bundle.
2152 * @see #sendOrderedBroadcastAsUser(Intent, UserHandle, String,
2153 * BroadcastReceiver, Handler, int, String, Bundle)
2156 public abstract void sendOrderedBroadcastAsUser(Intent intent, UserHandle user,
2157 @Nullable String receiverPermission, int appOp, @Nullable Bundle options,
2158 BroadcastReceiver resultReceiver, @Nullable Handler scheduler, int initialCode,
2159 @Nullable String initialData, @Nullable Bundle initialExtras);
2162 * <p>Perform a {@link #sendBroadcast(Intent)} that is "sticky," meaning the
2163 * Intent you are sending stays around after the broadcast is complete,
2164 * so that others can quickly retrieve that data through the return
2165 * value of {@link #registerReceiver(BroadcastReceiver, IntentFilter)}. In
2166 * all other ways, this behaves the same as
2167 * {@link #sendBroadcast(Intent)}.
2169 * <p>You must hold the {@link android.Manifest.permission#BROADCAST_STICKY}
2170 * permission in order to use this API. If you do not hold that
2171 * permission, {@link SecurityException} will be thrown.
2173 * @deprecated Sticky broadcasts should not be used. They provide no security (anyone
2174 * can access them), no protection (anyone can modify them), and many other problems.
2175 * The recommended pattern is to use a non-sticky broadcast to report that <em>something</em>
2176 * has changed, with another mechanism for apps to retrieve the current value whenever
2179 * @param intent The Intent to broadcast; all receivers matching this
2180 * Intent will receive the broadcast, and the Intent will be held to
2181 * be re-broadcast to future receivers.
2183 * @see #sendBroadcast(Intent)
2184 * @see #sendStickyOrderedBroadcast(Intent, BroadcastReceiver, Handler, int, String, Bundle)
2187 public abstract void sendStickyBroadcast(@RequiresPermission Intent intent);
2190 * <p>Version of {@link #sendStickyBroadcast} that allows you to
2191 * receive data back from the broadcast. This is accomplished by
2192 * supplying your own BroadcastReceiver when calling, which will be
2193 * treated as a final receiver at the end of the broadcast -- its
2194 * {@link BroadcastReceiver#onReceive} method will be called with
2195 * the result values collected from the other receivers. The broadcast will
2196 * be serialized in the same way as calling
2197 * {@link #sendOrderedBroadcast(Intent, String)}.
2199 * <p>Like {@link #sendBroadcast(Intent)}, this method is
2200 * asynchronous; it will return before
2201 * resultReceiver.onReceive() is called. Note that the sticky data
2202 * stored is only the data you initially supply to the broadcast, not
2203 * the result of any changes made by the receivers.
2205 * <p>See {@link BroadcastReceiver} for more information on Intent broadcasts.
2207 * @deprecated Sticky broadcasts should not be used. They provide no security (anyone
2208 * can access them), no protection (anyone can modify them), and many other problems.
2209 * The recommended pattern is to use a non-sticky broadcast to report that <em>something</em>
2210 * has changed, with another mechanism for apps to retrieve the current value whenever
2213 * @param intent The Intent to broadcast; all receivers matching this
2214 * Intent will receive the broadcast.
2215 * @param resultReceiver Your own BroadcastReceiver to treat as the final
2216 * receiver of the broadcast.
2217 * @param scheduler A custom Handler with which to schedule the
2218 * resultReceiver callback; if null it will be
2219 * scheduled in the Context's main thread.
2220 * @param initialCode An initial value for the result code. Often
2221 * Activity.RESULT_OK.
2222 * @param initialData An initial value for the result data. Often
2224 * @param initialExtras An initial value for the result extras. Often
2227 * @see #sendBroadcast(Intent)
2228 * @see #sendBroadcast(Intent, String)
2229 * @see #sendOrderedBroadcast(Intent, String)
2230 * @see #sendStickyBroadcast(Intent)
2231 * @see android.content.BroadcastReceiver
2232 * @see #registerReceiver
2233 * @see android.app.Activity#RESULT_OK
2236 public abstract void sendStickyOrderedBroadcast(@RequiresPermission Intent intent,
2237 BroadcastReceiver resultReceiver,
2238 @Nullable Handler scheduler, int initialCode, @Nullable String initialData,
2239 @Nullable Bundle initialExtras);
2242 * <p>Remove the data previously sent with {@link #sendStickyBroadcast},
2243 * so that it is as if the sticky broadcast had never happened.
2245 * <p>You must hold the {@link android.Manifest.permission#BROADCAST_STICKY}
2246 * permission in order to use this API. If you do not hold that
2247 * permission, {@link SecurityException} will be thrown.
2249 * @deprecated Sticky broadcasts should not be used. They provide no security (anyone
2250 * can access them), no protection (anyone can modify them), and many other problems.
2251 * The recommended pattern is to use a non-sticky broadcast to report that <em>something</em>
2252 * has changed, with another mechanism for apps to retrieve the current value whenever
2255 * @param intent The Intent that was previously broadcast.
2257 * @see #sendStickyBroadcast
2260 public abstract void removeStickyBroadcast(@RequiresPermission Intent intent);
2263 * <p>Version of {@link #sendStickyBroadcast(Intent)} that allows you to specify the
2264 * user the broadcast will be sent to. This is not available to applications
2265 * that are not pre-installed on the system image. Using it requires holding
2266 * the INTERACT_ACROSS_USERS permission.
2268 * @deprecated Sticky broadcasts should not be used. They provide no security (anyone
2269 * can access them), no protection (anyone can modify them), and many other problems.
2270 * The recommended pattern is to use a non-sticky broadcast to report that <em>something</em>
2271 * has changed, with another mechanism for apps to retrieve the current value whenever
2274 * @param intent The Intent to broadcast; all receivers matching this
2275 * Intent will receive the broadcast, and the Intent will be held to
2276 * be re-broadcast to future receivers.
2277 * @param user UserHandle to send the intent to.
2279 * @see #sendBroadcast(Intent)
2282 public abstract void sendStickyBroadcastAsUser(@RequiresPermission Intent intent,
2287 * This is just here for sending CONNECTIVITY_ACTION.
2290 public abstract void sendStickyBroadcastAsUser(@RequiresPermission Intent intent,
2291 UserHandle user, Bundle options);
2295 * {@link #sendStickyOrderedBroadcast(Intent, BroadcastReceiver, Handler, int, String, Bundle)}
2296 * that allows you to specify the
2297 * user the broadcast will be sent to. This is not available to applications
2298 * that are not pre-installed on the system image. Using it requires holding
2299 * the INTERACT_ACROSS_USERS permission.
2301 * <p>See {@link BroadcastReceiver} for more information on Intent broadcasts.
2303 * @deprecated Sticky broadcasts should not be used. They provide no security (anyone
2304 * can access them), no protection (anyone can modify them), and many other problems.
2305 * The recommended pattern is to use a non-sticky broadcast to report that <em>something</em>
2306 * has changed, with another mechanism for apps to retrieve the current value whenever
2309 * @param intent The Intent to broadcast; all receivers matching this
2310 * Intent will receive the broadcast.
2311 * @param user UserHandle to send the intent to.
2312 * @param resultReceiver Your own BroadcastReceiver to treat as the final
2313 * receiver of the broadcast.
2314 * @param scheduler A custom Handler with which to schedule the
2315 * resultReceiver callback; if null it will be
2316 * scheduled in the Context's main thread.
2317 * @param initialCode An initial value for the result code. Often
2318 * Activity.RESULT_OK.
2319 * @param initialData An initial value for the result data. Often
2321 * @param initialExtras An initial value for the result extras. Often
2324 * @see #sendStickyOrderedBroadcast(Intent, BroadcastReceiver, Handler, int, String, Bundle)
2327 public abstract void sendStickyOrderedBroadcastAsUser(@RequiresPermission Intent intent,
2328 UserHandle user, BroadcastReceiver resultReceiver,
2329 @Nullable Handler scheduler, int initialCode, @Nullable String initialData,
2330 @Nullable Bundle initialExtras);
2333 * <p>Version of {@link #removeStickyBroadcast(Intent)} that allows you to specify the
2334 * user the broadcast will be sent to. This is not available to applications
2335 * that are not pre-installed on the system image. Using it requires holding
2336 * the INTERACT_ACROSS_USERS permission.
2338 * <p>You must hold the {@link android.Manifest.permission#BROADCAST_STICKY}
2339 * permission in order to use this API. If you do not hold that
2340 * permission, {@link SecurityException} will be thrown.
2342 * @deprecated Sticky broadcasts should not be used. They provide no security (anyone
2343 * can access them), no protection (anyone can modify them), and many other problems.
2344 * The recommended pattern is to use a non-sticky broadcast to report that <em>something</em>
2345 * has changed, with another mechanism for apps to retrieve the current value whenever
2348 * @param intent The Intent that was previously broadcast.
2349 * @param user UserHandle to remove the sticky broadcast from.
2351 * @see #sendStickyBroadcastAsUser
2354 public abstract void removeStickyBroadcastAsUser(@RequiresPermission Intent intent,
2358 * Register a BroadcastReceiver to be run in the main activity thread. The
2359 * <var>receiver</var> will be called with any broadcast Intent that
2360 * matches <var>filter</var>, in the main application thread.
2362 * <p>The system may broadcast Intents that are "sticky" -- these stay
2363 * around after the broadcast has finished, to be sent to any later
2364 * registrations. If your IntentFilter matches one of these sticky
2365 * Intents, that Intent will be returned by this function
2366 * <strong>and</strong> sent to your <var>receiver</var> as if it had just
2369 * <p>There may be multiple sticky Intents that match <var>filter</var>,
2370 * in which case each of these will be sent to <var>receiver</var>. In
2371 * this case, only one of these can be returned directly by the function;
2372 * which of these that is returned is arbitrarily decided by the system.
2374 * <p>If you know the Intent your are registering for is sticky, you can
2375 * supply null for your <var>receiver</var>. In this case, no receiver is
2376 * registered -- the function simply returns the sticky Intent that
2377 * matches <var>filter</var>. In the case of multiple matches, the same
2378 * rules as described above apply.
2380 * <p>See {@link BroadcastReceiver} for more information on Intent broadcasts.
2382 * <p>As of {@link android.os.Build.VERSION_CODES#ICE_CREAM_SANDWICH}, receivers
2383 * registered with this method will correctly respect the
2384 * {@link Intent#setPackage(String)} specified for an Intent being broadcast.
2385 * Prior to that, it would be ignored and delivered to all matching registered
2386 * receivers. Be careful if using this for security.</p>
2388 * <p class="note">Note: this method <em>cannot be called from a
2389 * {@link BroadcastReceiver} component;</em> that is, from a BroadcastReceiver
2390 * that is declared in an application's manifest. It is okay, however, to call
2391 * this method from another BroadcastReceiver that has itself been registered
2392 * at run time with {@link #registerReceiver}, since the lifetime of such a
2393 * registered BroadcastReceiver is tied to the object that registered it.</p>
2395 * @param receiver The BroadcastReceiver to handle the broadcast.
2396 * @param filter Selects the Intent broadcasts to be received.
2398 * @return The first sticky intent found that matches <var>filter</var>,
2399 * or null if there are none.
2401 * @see #registerReceiver(BroadcastReceiver, IntentFilter, String, Handler)
2402 * @see #sendBroadcast
2403 * @see #unregisterReceiver
2406 public abstract Intent registerReceiver(@Nullable BroadcastReceiver receiver,
2407 IntentFilter filter);
2410 * Register to receive intent broadcasts, with the receiver optionally being
2411 * exposed to Instant Apps. See
2412 * {@link #registerReceiver(BroadcastReceiver, IntentFilter)} for more
2413 * information. By default Instant Apps cannot interact with receivers in other
2414 * applications, this allows you to expose a receiver that Instant Apps can
2417 * <p>See {@link BroadcastReceiver} for more information on Intent broadcasts.
2419 * <p>As of {@link android.os.Build.VERSION_CODES#ICE_CREAM_SANDWICH}, receivers
2420 * registered with this method will correctly respect the
2421 * {@link Intent#setPackage(String)} specified for an Intent being broadcast.
2422 * Prior to that, it would be ignored and delivered to all matching registered
2423 * receivers. Be careful if using this for security.</p>
2425 * @param receiver The BroadcastReceiver to handle the broadcast.
2426 * @param filter Selects the Intent broadcasts to be received.
2427 * @param visibleToInstantApps If the receiver accepts broadcasts from Instant Apps.
2429 * @return The first sticky intent found that matches <var>filter</var>,
2430 * or null if there are none.
2432 * @see #registerReceiver(BroadcastReceiver, IntentFilter)
2433 * @see #sendBroadcast
2434 * @see #unregisterReceiver
2437 public abstract Intent registerReceiver(@Nullable BroadcastReceiver receiver,
2438 IntentFilter filter,
2439 boolean visibleToInstantApps);
2442 * Register to receive intent broadcasts, to run in the context of
2443 * <var>scheduler</var>. See
2444 * {@link #registerReceiver(BroadcastReceiver, IntentFilter)} for more
2445 * information. This allows you to enforce permissions on who can
2446 * broadcast intents to your receiver, or have the receiver run in
2447 * a different thread than the main application thread.
2449 * <p>See {@link BroadcastReceiver} for more information on Intent broadcasts.
2451 * <p>As of {@link android.os.Build.VERSION_CODES#ICE_CREAM_SANDWICH}, receivers
2452 * registered with this method will correctly respect the
2453 * {@link Intent#setPackage(String)} specified for an Intent being broadcast.
2454 * Prior to that, it would be ignored and delivered to all matching registered
2455 * receivers. Be careful if using this for security.</p>
2457 * @param receiver The BroadcastReceiver to handle the broadcast.
2458 * @param filter Selects the Intent broadcasts to be received.
2459 * @param broadcastPermission String naming a permissions that a
2460 * broadcaster must hold in order to send an Intent to you. If null,
2461 * no permission is required.
2462 * @param scheduler Handler identifying the thread that will receive
2463 * the Intent. If null, the main thread of the process will be used.
2465 * @return The first sticky intent found that matches <var>filter</var>,
2466 * or null if there are none.
2468 * @see #registerReceiver(BroadcastReceiver, IntentFilter)
2469 * @see #sendBroadcast
2470 * @see #unregisterReceiver
2473 public abstract Intent registerReceiver(BroadcastReceiver receiver,
2474 IntentFilter filter, @Nullable String broadcastPermission,
2475 @Nullable Handler scheduler);
2478 * Register to receive intent broadcasts, with the receiver optionally being
2479 * exposed to Instant Apps. See
2480 * {@link #registerReceiver(BroadcastReceiver, IntentFilter, boolean)} and
2481 * {@link #registerReceiver(BroadcastReceiver, IntentFilter, String, Handler)}
2482 * for more information.
2484 * <p>See {@link BroadcastReceiver} for more information on Intent broadcasts.
2486 * <p>As of {@link android.os.Build.VERSION_CODES#ICE_CREAM_SANDWICH}, receivers
2487 * registered with this method will correctly respect the
2488 * {@link Intent#setPackage(String)} specified for an Intent being broadcast.
2489 * Prior to that, it would be ignored and delivered to all matching registered
2490 * receivers. Be careful if using this for security.</p>
2492 * @param receiver The BroadcastReceiver to handle the broadcast.
2493 * @param filter Selects the Intent broadcasts to be received.
2494 * @param broadcastPermission String naming a permissions that a
2495 * broadcaster must hold in order to send an Intent to you. If null,
2496 * no permission is required.
2497 * @param scheduler Handler identifying the thread that will receive
2498 * the Intent. If null, the main thread of the process will be used.
2499 * @param visibleToInstantApps If the receiver accepts broadcasts from Instant Apps.
2501 * @return The first sticky intent found that matches <var>filter</var>,
2502 * or null if there are none.
2504 * @see #registerReceiver(BroadcastReceiver, IntentFilter, boolean)
2505 * @see #registerReceiver(BroadcastReceiver, IntentFilter, String, Handler)
2506 * @see #sendBroadcast
2507 * @see #unregisterReceiver
2510 public abstract Intent registerReceiver(BroadcastReceiver receiver,
2511 IntentFilter filter, @Nullable String broadcastPermission,
2512 @Nullable Handler scheduler, boolean visibleToInstantApps);
2516 * Same as {@link #registerReceiver(BroadcastReceiver, IntentFilter, String, Handler)
2517 * but for a specific user. This receiver will receiver broadcasts that
2518 * are sent to the requested user. It
2519 * requires holding the {@link android.Manifest.permission#INTERACT_ACROSS_USERS_FULL}
2522 * @param receiver The BroadcastReceiver to handle the broadcast.
2523 * @param user UserHandle to send the intent to.
2524 * @param filter Selects the Intent broadcasts to be received.
2525 * @param broadcastPermission String naming a permissions that a
2526 * broadcaster must hold in order to send an Intent to you. If null,
2527 * no permission is required.
2528 * @param scheduler Handler identifying the thread that will receive
2529 * the Intent. If null, the main thread of the process will be used.
2531 * @return The first sticky intent found that matches <var>filter</var>,
2532 * or null if there are none.
2534 * @see #registerReceiver(BroadcastReceiver, IntentFilter, String, Handler)
2535 * @see #sendBroadcast
2536 * @see #unregisterReceiver
2539 public abstract Intent registerReceiverAsUser(BroadcastReceiver receiver,
2540 UserHandle user, IntentFilter filter, @Nullable String broadcastPermission,
2541 @Nullable Handler scheduler);
2544 * Unregister a previously registered BroadcastReceiver. <em>All</em>
2545 * filters that have been registered for this BroadcastReceiver will be
2548 * @param receiver The BroadcastReceiver to unregister.
2550 * @see #registerReceiver
2552 public abstract void unregisterReceiver(BroadcastReceiver receiver);
2555 * Request that a given application service be started. The Intent
2556 * should either contain the complete class name of a specific service
2557 * implementation to start, or a specific package name to target. If the
2558 * Intent is less specified, it logs a warning about this. In this case any of the
2559 * multiple matching services may be used. If this service
2560 * is not already running, it will be instantiated and started (creating a
2561 * process for it if needed); if it is running then it remains running.
2563 * <p>Every call to this method will result in a corresponding call to
2564 * the target service's {@link android.app.Service#onStartCommand} method,
2565 * with the <var>intent</var> given here. This provides a convenient way
2566 * to submit jobs to a service without having to bind and call on to its
2569 * <p>Using startService() overrides the default service lifetime that is
2570 * managed by {@link #bindService}: it requires the service to remain
2571 * running until {@link #stopService} is called, regardless of whether
2572 * any clients are connected to it. Note that calls to startService()
2573 * do not nest: no matter how many times you call startService(),
2574 * a single call to {@link #stopService} will stop it.
2576 * <p>The system attempts to keep running services around as much as
2577 * possible. The only time they should be stopped is if the current
2578 * foreground application is using so many resources that the service needs
2579 * to be killed. If any errors happen in the service's process, it will
2580 * automatically be restarted.
2582 * <p>This function will throw {@link SecurityException} if you do not
2583 * have permission to start the given service.
2585 * <p class="note"><strong>Note:</strong> Each call to startService()
2586 * results in significant work done by the system to manage service
2587 * lifecycle surrounding the processing of the intent, which can take
2588 * multiple milliseconds of CPU time. Due to this cost, startService()
2589 * should not be used for frequent intent delivery to a service, and only
2590 * for scheduling significant work. Use {@link #bindService bound services}
2591 * for high frequency calls.
2594 * @param service Identifies the service to be started. The Intent must be
2595 * fully explicit (supplying a component name). Additional values
2596 * may be included in the Intent extras to supply arguments along with
2597 * this specific start call.
2599 * @return If the service is being started or is already running, the
2600 * {@link ComponentName} of the actual service that was started is
2601 * returned; else if the service does not exist null is returned.
2603 * @throws SecurityException If the caller does not have permission to access the service
2604 * or the service can not be found.
2605 * @throws IllegalStateException If the application is in a state where the service
2606 * can not be started (such as not in the foreground in a state when services are allowed).
2612 public abstract ComponentName startService(Intent service);
2615 * Similar to {@link #startService(Intent)}, but with an implicit promise that the
2616 * Service will call {@link android.app.Service#startForeground(int, Notification)
2617 * startForeground(int, Notification)} once it begins running. The service is given
2618 * an amount of time comparable to the ANR interval to do this, otherwise the system
2619 * will automatically stop the service and declare the app ANR.
2621 * <p>Unlike the ordinary {@link #startService(Intent)}, this method can be used
2622 * at any time, regardless of whether the app hosting the service is in a foreground
2625 * @param service Identifies the service to be started. The Intent must be
2626 * fully explicit (supplying a component name). Additional values
2627 * may be included in the Intent extras to supply arguments along with
2628 * this specific start call.
2630 * @return If the service is being started or is already running, the
2631 * {@link ComponentName} of the actual service that was started is
2632 * returned; else if the service does not exist null is returned.
2634 * @throws SecurityException If the caller does not have permission to access the service
2635 * or the service can not be found.
2638 * @see android.app.Service#startForeground(int, Notification)
2641 public abstract ComponentName startForegroundService(Intent service);
2644 * @hide like {@link #startForegroundService(Intent)} but for a specific user.
2647 public abstract ComponentName startForegroundServiceAsUser(Intent service, UserHandle user);
2650 * Request that a given application service be stopped. If the service is
2651 * not running, nothing happens. Otherwise it is stopped. Note that calls
2652 * to startService() are not counted -- this stops the service no matter
2653 * how many times it was started.
2655 * <p>Note that if a stopped service still has {@link ServiceConnection}
2656 * objects bound to it with the {@link #BIND_AUTO_CREATE} set, it will
2657 * not be destroyed until all of these bindings are removed. See
2658 * the {@link android.app.Service} documentation for more details on a
2659 * service's lifecycle.
2661 * <p>This function will throw {@link SecurityException} if you do not
2662 * have permission to stop the given service.
2664 * @param service Description of the service to be stopped. The Intent must be either
2665 * fully explicit (supplying a component name) or specify a specific package
2666 * name it is targetted to.
2668 * @return If there is a service matching the given Intent that is already
2669 * running, then it is stopped and {@code true} is returned; else {@code false} is returned.
2671 * @throws SecurityException If the caller does not have permission to access the service
2672 * or the service can not be found.
2673 * @throws IllegalStateException If the application is in a state where the service
2674 * can not be started (such as not in the foreground in a state when services are allowed).
2676 * @see #startService
2678 public abstract boolean stopService(Intent service);
2681 * @hide like {@link #startService(Intent)} but for a specific user.
2684 public abstract ComponentName startServiceAsUser(Intent service, UserHandle user);
2687 * @hide like {@link #stopService(Intent)} but for a specific user.
2689 public abstract boolean stopServiceAsUser(Intent service, UserHandle user);
2692 * Connect to an application service, creating it if needed. This defines
2693 * a dependency between your application and the service. The given
2694 * <var>conn</var> will receive the service object when it is created and be
2695 * told if it dies and restarts. The service will be considered required
2696 * by the system only for as long as the calling context exists. For
2697 * example, if this Context is an Activity that is stopped, the service will
2698 * not be required to continue running until the Activity is resumed.
2700 * <p>This function will throw {@link SecurityException} if you do not
2701 * have permission to bind to the given service.
2703 * <p class="note">Note: this method <em>can not be called from a
2704 * {@link BroadcastReceiver} component</em>. A pattern you can use to
2705 * communicate from a BroadcastReceiver to a Service is to call
2706 * {@link #startService} with the arguments containing the command to be
2707 * sent, with the service calling its
2708 * {@link android.app.Service#stopSelf(int)} method when done executing
2709 * that command. See the API demo App/Service/Service Start Arguments
2710 * Controller for an illustration of this. It is okay, however, to use
2711 * this method from a BroadcastReceiver that has been registered with
2712 * {@link #registerReceiver}, since the lifetime of this BroadcastReceiver
2713 * is tied to another object (the one that registered it).</p>
2715 * @param service Identifies the service to connect to. The Intent must
2716 * specify an explicit component name.
2717 * @param conn Receives information as the service is started and stopped.
2718 * This must be a valid ServiceConnection object; it must not be null.
2719 * @param flags Operation options for the binding. May be 0,
2720 * {@link #BIND_AUTO_CREATE}, {@link #BIND_DEBUG_UNBIND},
2721 * {@link #BIND_NOT_FOREGROUND}, {@link #BIND_ABOVE_CLIENT},
2722 * {@link #BIND_ALLOW_OOM_MANAGEMENT}, or
2723 * {@link #BIND_WAIVE_PRIORITY}.
2724 * @return If you have successfully bound to the service, {@code true} is returned;
2725 * {@code false} is returned if the connection is not made so you will not
2726 * receive the service object. However, you should still call
2727 * {@link #unbindService} to release the connection.
2729 * @throws SecurityException If the caller does not have permission to access the service
2730 * or the service can not be found.
2732 * @see #unbindService
2733 * @see #startService
2734 * @see #BIND_AUTO_CREATE
2735 * @see #BIND_DEBUG_UNBIND
2736 * @see #BIND_NOT_FOREGROUND
2738 public abstract boolean bindService(@RequiresPermission Intent service,
2739 @NonNull ServiceConnection conn, @BindServiceFlags int flags);
2742 * Same as {@link #bindService(Intent, ServiceConnection, int)}, but with an explicit userHandle
2743 * argument for use by system server and other multi-user aware code.
2747 @SuppressWarnings("unused")
2748 public boolean bindServiceAsUser(@RequiresPermission Intent service, ServiceConnection conn,
2749 int flags, UserHandle user) {
2750 throw new RuntimeException("Not implemented. Must override in a subclass.");
2754 * Same as {@link #bindService(Intent, ServiceConnection, int, UserHandle)}, but with an
2755 * explicit non-null Handler to run the ServiceConnection callbacks on.
2759 public boolean bindServiceAsUser(Intent service, ServiceConnection conn, int flags,
2760 Handler handler, UserHandle user) {
2761 throw new RuntimeException("Not implemented. Must override in a subclass.");
2765 * Disconnect from an application service. You will no longer receive
2766 * calls as the service is restarted, and the service is now allowed to
2769 * @param conn The connection interface previously supplied to
2770 * bindService(). This parameter must not be null.
2774 public abstract void unbindService(@NonNull ServiceConnection conn);
2777 * Start executing an {@link android.app.Instrumentation} class. The given
2778 * Instrumentation component will be run by killing its target application
2779 * (if currently running), starting the target process, instantiating the
2780 * instrumentation component, and then letting it drive the application.
2782 * <p>This function is not synchronous -- it returns as soon as the
2783 * instrumentation has started and while it is running.
2785 * <p>Instrumentation is normally only allowed to run against a package
2786 * that is either unsigned or signed with a signature that the
2787 * the instrumentation package is also signed with (ensuring the target
2788 * trusts the instrumentation).
2790 * @param className Name of the Instrumentation component to be run.
2791 * @param profileFile Optional path to write profiling data as the
2792 * instrumentation runs, or null for no profiling.
2793 * @param arguments Additional optional arguments to pass to the
2794 * instrumentation, or null.
2796 * @return {@code true} if the instrumentation was successfully started,
2797 * else {@code false} if it could not be found.
2799 public abstract boolean startInstrumentation(@NonNull ComponentName className,
2800 @Nullable String profileFile, @Nullable Bundle arguments);
2806 LAYOUT_INFLATER_SERVICE,
2810 NOTIFICATION_SERVICE,
2811 ACCESSIBILITY_SERVICE,
2815 //@hide: COUNTRY_DETECTOR,
2819 STORAGE_STATS_SERVICE,
2822 //@hide: STATUS_BAR_SERVICE,
2823 CONNECTIVITY_SERVICE,
2825 //@hide: UPDATE_LOCK_SERVICE,
2826 //@hide: NETWORKMANAGEMENT_SERVICE,
2827 NETWORK_STATS_SERVICE,
2828 //@hide: NETWORK_POLICY_SERVICE,
2832 WIFI_SCANNING_SERVICE,
2833 //@hide: WIFI_RTT_SERVICE,
2834 //@hide: ETHERNET_SERVICE,
2838 FINGERPRINT_SERVICE,
2839 MEDIA_ROUTER_SERVICE,
2841 TELEPHONY_SUBSCRIPTION_SERVICE,
2842 CARRIER_CONFIG_SERVICE,
2845 INPUT_METHOD_SERVICE,
2846 TEXT_SERVICES_MANAGER_SERVICE,
2848 //@hide: VOICE_INTERACTION_MANAGER_SERVICE,
2849 //@hide: BACKUP_SERVICE,
2851 //@hide: DEVICE_IDLE_CONTROLLER,
2852 DEVICE_POLICY_SERVICE,
2857 //@hide: SIP_SERVICE,
2859 LAUNCHER_APPS_SERVICE,
2860 //@hide: SERIAL_SERVICE,
2861 //@hide: HDMI_CONTROL_SERVICE,
2865 RESTRICTIONS_SERVICE,
2869 CONSUMER_IR_SERVICE,
2870 //@hide: TRUST_SERVICE,
2872 //@hide: NETWORK_SCORE_SERVICE,
2873 USAGE_STATS_SERVICE,
2874 MEDIA_SESSION_SERVICE,
2876 JOB_SCHEDULER_SERVICE,
2877 //@hide: PERSISTENT_DATA_BLOCK_SERVICE,
2878 //@hide: OEM_LOCK_SERVICE,
2879 MEDIA_PROJECTION_SERVICE,
2882 HARDWARE_PROPERTIES_SERVICE,
2883 //@hide: SOUND_TRIGGER_SERVICE,
2885 //@hide: CONTEXTHUB_SERVICE,
2886 SYSTEM_HEALTH_SERVICE,
2887 //@hide: INCIDENT_SERVICE
2889 @Retention(RetentionPolicy.SOURCE)
2890 public @interface ServiceName {}
2893 * Return the handle to a system-level service by name. The class of the
2894 * returned object varies by the requested name. Currently available names
2898 * <dt> {@link #WINDOW_SERVICE} ("window")
2899 * <dd> The top-level window manager in which you can place custom
2900 * windows. The returned object is a {@link android.view.WindowManager}.
2901 * <dt> {@link #LAYOUT_INFLATER_SERVICE} ("layout_inflater")
2902 * <dd> A {@link android.view.LayoutInflater} for inflating layout resources
2904 * <dt> {@link #ACTIVITY_SERVICE} ("activity")
2905 * <dd> A {@link android.app.ActivityManager} for interacting with the
2906 * global activity state of the system.
2907 * <dt> {@link #POWER_SERVICE} ("power")
2908 * <dd> A {@link android.os.PowerManager} for controlling power
2910 * <dt> {@link #ALARM_SERVICE} ("alarm")
2911 * <dd> A {@link android.app.AlarmManager} for receiving intents at the
2912 * time of your choosing.
2913 * <dt> {@link #NOTIFICATION_SERVICE} ("notification")
2914 * <dd> A {@link android.app.NotificationManager} for informing the user
2915 * of background events.
2916 * <dt> {@link #KEYGUARD_SERVICE} ("keyguard")
2917 * <dd> A {@link android.app.KeyguardManager} for controlling keyguard.
2918 * <dt> {@link #LOCATION_SERVICE} ("location")
2919 * <dd> A {@link android.location.LocationManager} for controlling location
2920 * (e.g., GPS) updates.
2921 * <dt> {@link #SEARCH_SERVICE} ("search")
2922 * <dd> A {@link android.app.SearchManager} for handling search.
2923 * <dt> {@link #VIBRATOR_SERVICE} ("vibrator")
2924 * <dd> A {@link android.os.Vibrator} for interacting with the vibrator
2926 * <dt> {@link #CONNECTIVITY_SERVICE} ("connection")
2927 * <dd> A {@link android.net.ConnectivityManager ConnectivityManager} for
2928 * handling management of network connections.
2929 * <dt> {@link #IPSEC_SERVICE} ("ipsec")
2930 * <dd> A {@link android.net.IpSecManager IpSecManager} for managing IPSec on
2931 * sockets and networks.
2932 * <dt> {@link #WIFI_SERVICE} ("wifi")
2933 * <dd> A {@link android.net.wifi.WifiManager WifiManager} for management of Wi-Fi
2934 * connectivity. On releases before NYC, it should only be obtained from an application
2935 * context, and not from any other derived context to avoid memory leaks within the calling
2937 * <dt> {@link #WIFI_AWARE_SERVICE} ("wifiaware")
2938 * <dd> A {@link android.net.wifi.aware.WifiAwareManager WifiAwareManager} for management of
2939 * Wi-Fi Aware discovery and connectivity.
2940 * <dt> {@link #WIFI_P2P_SERVICE} ("wifip2p")
2941 * <dd> A {@link android.net.wifi.p2p.WifiP2pManager WifiP2pManager} for management of
2942 * Wi-Fi Direct connectivity.
2943 * <dt> {@link #INPUT_METHOD_SERVICE} ("input_method")
2944 * <dd> An {@link android.view.inputmethod.InputMethodManager InputMethodManager}
2945 * for management of input methods.
2946 * <dt> {@link #UI_MODE_SERVICE} ("uimode")
2947 * <dd> An {@link android.app.UiModeManager} for controlling UI modes.
2948 * <dt> {@link #DOWNLOAD_SERVICE} ("download")
2949 * <dd> A {@link android.app.DownloadManager} for requesting HTTP downloads
2950 * <dt> {@link #BATTERY_SERVICE} ("batterymanager")
2951 * <dd> A {@link android.os.BatteryManager} for managing battery state
2952 * <dt> {@link #JOB_SCHEDULER_SERVICE} ("taskmanager")
2953 * <dd> A {@link android.app.job.JobScheduler} for managing scheduled tasks
2954 * <dt> {@link #NETWORK_STATS_SERVICE} ("netstats")
2955 * <dd> A {@link android.app.usage.NetworkStatsManager NetworkStatsManager} for querying network
2957 * <dt> {@link #HARDWARE_PROPERTIES_SERVICE} ("hardware_properties")
2958 * <dd> A {@link android.os.HardwarePropertiesManager} for accessing hardware properties.
2961 * <p>Note: System services obtained via this API may be closely associated with
2962 * the Context in which they are obtained from. In general, do not share the
2963 * service objects between various different contexts (Activities, Applications,
2964 * Services, Providers, etc.)
2966 * @param name The name of the desired service.
2968 * @return The service or null if the name does not exist.
2970 * @see #WINDOW_SERVICE
2971 * @see android.view.WindowManager
2972 * @see #LAYOUT_INFLATER_SERVICE
2973 * @see android.view.LayoutInflater
2974 * @see #ACTIVITY_SERVICE
2975 * @see android.app.ActivityManager
2976 * @see #POWER_SERVICE
2977 * @see android.os.PowerManager
2978 * @see #ALARM_SERVICE
2979 * @see android.app.AlarmManager
2980 * @see #NOTIFICATION_SERVICE
2981 * @see android.app.NotificationManager
2982 * @see #KEYGUARD_SERVICE
2983 * @see android.app.KeyguardManager
2984 * @see #LOCATION_SERVICE
2985 * @see android.location.LocationManager
2986 * @see #SEARCH_SERVICE
2987 * @see android.app.SearchManager
2988 * @see #SENSOR_SERVICE
2989 * @see android.hardware.SensorManager
2990 * @see #STORAGE_SERVICE
2991 * @see android.os.storage.StorageManager
2992 * @see #VIBRATOR_SERVICE
2993 * @see android.os.Vibrator
2994 * @see #CONNECTIVITY_SERVICE
2995 * @see android.net.ConnectivityManager
2996 * @see #WIFI_SERVICE
2997 * @see android.net.wifi.WifiManager
2998 * @see #AUDIO_SERVICE
2999 * @see android.media.AudioManager
3000 * @see #MEDIA_ROUTER_SERVICE
3001 * @see android.media.MediaRouter
3002 * @see #TELEPHONY_SERVICE
3003 * @see android.telephony.TelephonyManager
3004 * @see #TELEPHONY_SUBSCRIPTION_SERVICE
3005 * @see android.telephony.SubscriptionManager
3006 * @see #CARRIER_CONFIG_SERVICE
3007 * @see android.telephony.CarrierConfigManager
3008 * @see #INPUT_METHOD_SERVICE
3009 * @see android.view.inputmethod.InputMethodManager
3010 * @see #UI_MODE_SERVICE
3011 * @see android.app.UiModeManager
3012 * @see #DOWNLOAD_SERVICE
3013 * @see android.app.DownloadManager
3014 * @see #BATTERY_SERVICE
3015 * @see android.os.BatteryManager
3016 * @see #JOB_SCHEDULER_SERVICE
3017 * @see android.app.job.JobScheduler
3018 * @see #NETWORK_STATS_SERVICE
3019 * @see android.app.usage.NetworkStatsManager
3020 * @see android.os.HardwarePropertiesManager
3021 * @see #HARDWARE_PROPERTIES_SERVICE
3023 public abstract Object getSystemService(@ServiceName @NonNull String name);
3026 * Return the handle to a system-level service by class.
3028 * Currently available classes are:
3029 * {@link android.view.WindowManager}, {@link android.view.LayoutInflater},
3030 * {@link android.app.ActivityManager}, {@link android.os.PowerManager},
3031 * {@link android.app.AlarmManager}, {@link android.app.NotificationManager},
3032 * {@link android.app.KeyguardManager}, {@link android.location.LocationManager},
3033 * {@link android.app.SearchManager}, {@link android.os.Vibrator},
3034 * {@link android.net.ConnectivityManager},
3035 * {@link android.net.wifi.WifiManager},
3036 * {@link android.media.AudioManager}, {@link android.media.MediaRouter},
3037 * {@link android.telephony.TelephonyManager}, {@link android.telephony.SubscriptionManager},
3038 * {@link android.view.inputmethod.InputMethodManager},
3039 * {@link android.app.UiModeManager}, {@link android.app.DownloadManager},
3040 * {@link android.os.BatteryManager}, {@link android.app.job.JobScheduler},
3041 * {@link android.app.usage.NetworkStatsManager}.
3043 * Note: System services obtained via this API may be closely associated with
3044 * the Context in which they are obtained from. In general, do not share the
3045 * service objects between various different contexts (Activities, Applications,
3046 * Services, Providers, etc.)
3049 * @param serviceClass The class of the desired service.
3050 * @return The service or null if the class is not a supported system service.
3052 @SuppressWarnings("unchecked")
3053 public final <T> T getSystemService(Class<T> serviceClass) {
3054 // Because subclasses may override getSystemService(String) we cannot
3055 // perform a lookup by class alone. We must first map the class to its
3056 // service name then invoke the string-based method.
3057 String serviceName = getSystemServiceName(serviceClass);
3058 return serviceName != null ? (T)getSystemService(serviceName) : null;
3062 * Gets the name of the system-level service that is represented by the specified class.
3064 * @param serviceClass The class of the desired service.
3065 * @return The service name or null if the class is not a supported system service.
3067 public abstract String getSystemServiceName(Class<?> serviceClass);
3070 * Use with {@link #getSystemService} to retrieve a
3071 * {@link android.os.PowerManager} for controlling power management,
3072 * including "wake locks," which let you keep the device on while
3073 * you're running long tasks.
3075 public static final String POWER_SERVICE = "power";
3078 * Use with {@link #getSystemService} to retrieve a
3079 * {@link android.os.RecoverySystem} for accessing the recovery system
3082 * @see #getSystemService
3085 public static final String RECOVERY_SERVICE = "recovery";
3088 * Use with {@link #getSystemService} to retrieve a
3089 * {@link android.view.WindowManager} for accessing the system's window
3092 * @see #getSystemService
3093 * @see android.view.WindowManager
3095 public static final String WINDOW_SERVICE = "window";
3098 * Use with {@link #getSystemService} to retrieve a
3099 * {@link android.view.LayoutInflater} for inflating layout resources in this
3102 * @see #getSystemService
3103 * @see android.view.LayoutInflater
3105 public static final String LAYOUT_INFLATER_SERVICE = "layout_inflater";
3108 * Use with {@link #getSystemService} to retrieve a
3109 * {@link android.accounts.AccountManager} for receiving intents at a
3110 * time of your choosing.
3112 * @see #getSystemService
3113 * @see android.accounts.AccountManager
3115 public static final String ACCOUNT_SERVICE = "account";
3118 * Use with {@link #getSystemService} to retrieve a
3119 * {@link android.app.ActivityManager} for interacting with the global
3122 * @see #getSystemService
3123 * @see android.app.ActivityManager
3125 public static final String ACTIVITY_SERVICE = "activity";
3128 * Use with {@link #getSystemService} to retrieve a
3129 * {@link android.app.AlarmManager} for receiving intents at a
3130 * time of your choosing.
3132 * @see #getSystemService
3133 * @see android.app.AlarmManager
3135 public static final String ALARM_SERVICE = "alarm";
3138 * Use with {@link #getSystemService} to retrieve a
3139 * {@link android.app.NotificationManager} for informing the user of
3140 * background events.
3142 * @see #getSystemService
3143 * @see android.app.NotificationManager
3145 public static final String NOTIFICATION_SERVICE = "notification";
3148 * Use with {@link #getSystemService} to retrieve a
3149 * {@link android.view.accessibility.AccessibilityManager} for giving the user
3150 * feedback for UI events through the registered event listeners.
3152 * @see #getSystemService
3153 * @see android.view.accessibility.AccessibilityManager
3155 public static final String ACCESSIBILITY_SERVICE = "accessibility";
3158 * Use with {@link #getSystemService} to retrieve a
3159 * {@link android.view.accessibility.CaptioningManager} for obtaining
3160 * captioning properties and listening for changes in captioning
3163 * @see #getSystemService
3164 * @see android.view.accessibility.CaptioningManager
3166 public static final String CAPTIONING_SERVICE = "captioning";
3169 * Use with {@link #getSystemService} to retrieve a
3170 * {@link android.app.NotificationManager} for controlling keyguard.
3172 * @see #getSystemService
3173 * @see android.app.KeyguardManager
3175 public static final String KEYGUARD_SERVICE = "keyguard";
3178 * Use with {@link #getSystemService} to retrieve a {@link
3179 * android.location.LocationManager} for controlling location
3182 * @see #getSystemService
3183 * @see android.location.LocationManager
3185 public static final String LOCATION_SERVICE = "location";
3188 * Use with {@link #getSystemService} to retrieve a
3189 * {@link android.location.CountryDetector} for detecting the country that
3194 public static final String COUNTRY_DETECTOR = "country_detector";
3197 * Use with {@link #getSystemService} to retrieve a {@link
3198 * android.app.SearchManager} for handling searches.
3200 * @see #getSystemService
3201 * @see android.app.SearchManager
3203 public static final String SEARCH_SERVICE = "search";
3206 * Use with {@link #getSystemService} to retrieve a {@link
3207 * android.hardware.SensorManager} for accessing sensors.
3209 * @see #getSystemService
3210 * @see android.hardware.SensorManager
3212 public static final String SENSOR_SERVICE = "sensor";
3215 * Use with {@link #getSystemService} to retrieve a {@link
3216 * android.os.storage.StorageManager} for accessing system storage
3219 * @see #getSystemService
3220 * @see android.os.storage.StorageManager
3222 public static final String STORAGE_SERVICE = "storage";
3225 * Use with {@link #getSystemService} to retrieve a {@link
3226 * android.app.usage.StorageStatsManager} for accessing system storage
3229 * @see #getSystemService
3230 * @see android.app.usage.StorageStatsManager
3232 public static final String STORAGE_STATS_SERVICE = "storagestats";
3235 * Use with {@link #getSystemService} to retrieve a
3236 * com.android.server.WallpaperService for accessing wallpapers.
3238 * @see #getSystemService
3240 public static final String WALLPAPER_SERVICE = "wallpaper";
3243 * Use with {@link #getSystemService} to retrieve a {@link
3244 * android.os.Vibrator} for interacting with the vibration hardware.
3246 * @see #getSystemService
3247 * @see android.os.Vibrator
3249 public static final String VIBRATOR_SERVICE = "vibrator";
3252 * Use with {@link #getSystemService} to retrieve a {@link
3253 * android.app.StatusBarManager} for interacting with the status bar.
3255 * @see #getSystemService
3256 * @see android.app.StatusBarManager
3259 public static final String STATUS_BAR_SERVICE = "statusbar";
3262 * Use with {@link #getSystemService} to retrieve a {@link
3263 * android.net.ConnectivityManager} for handling management of
3264 * network connections.
3266 * @see #getSystemService
3267 * @see android.net.ConnectivityManager
3269 public static final String CONNECTIVITY_SERVICE = "connectivity";
3272 * Use with {@link #getSystemService} to retrieve a
3273 * {@link android.net.IpSecManager} for encrypting Sockets or Networks with
3276 * @see #getSystemService
3278 public static final String IPSEC_SERVICE = "ipsec";
3281 * Use with {@link #getSystemService} to retrieve a {@link
3282 * android.os.IUpdateLock} for managing runtime sequences that
3283 * must not be interrupted by headless OTA application or similar.
3286 * @see #getSystemService
3287 * @see android.os.UpdateLock
3289 public static final String UPDATE_LOCK_SERVICE = "updatelock";
3292 * Constant for the internal network management service, not really a Context service.
3295 public static final String NETWORKMANAGEMENT_SERVICE = "network_management";
3298 * Use with {@link #getSystemService} to retrieve a {@link
3299 * android.app.usage.NetworkStatsManager} for querying network usage stats.
3301 * @see #getSystemService
3302 * @see android.app.usage.NetworkStatsManager
3304 public static final String NETWORK_STATS_SERVICE = "netstats";
3306 public static final String NETWORK_POLICY_SERVICE = "netpolicy";
3309 * Use with {@link #getSystemService} to retrieve a {@link
3310 * android.net.wifi.WifiManager} for handling management of
3313 * @see #getSystemService
3314 * @see android.net.wifi.WifiManager
3316 public static final String WIFI_SERVICE = "wifi";
3319 * Use with {@link #getSystemService} to retrieve a {@link
3320 * android.net.wifi.p2p.WifiP2pManager} for handling management of
3321 * Wi-Fi peer-to-peer connections.
3323 * @see #getSystemService
3324 * @see android.net.wifi.p2p.WifiP2pManager
3326 public static final String WIFI_P2P_SERVICE = "wifip2p";
3329 * Use with {@link #getSystemService} to retrieve a
3330 * {@link android.net.wifi.aware.WifiAwareManager} for handling management of
3333 * @see #getSystemService
3334 * @see android.net.wifi.aware.WifiAwareManager
3336 public static final String WIFI_AWARE_SERVICE = "wifiaware";
3339 * Use with {@link #getSystemService} to retrieve a {@link
3340 * android.net.wifi.WifiScanner} for scanning the wifi universe
3342 * @see #getSystemService
3343 * @see android.net.wifi.WifiScanner
3347 public static final String WIFI_SCANNING_SERVICE = "wifiscanner";
3350 * Use with {@link #getSystemService} to retrieve a {@link
3351 * android.net.wifi.RttManager} for ranging devices with wifi
3353 * @see #getSystemService
3354 * @see android.net.wifi.RttManager
3358 public static final String WIFI_RTT_SERVICE = "rttmanager";
3361 * Use with {@link #getSystemService} to retrieve a {@link
3362 * android.net.EthernetManager} for handling management of
3365 * @see #getSystemService
3366 * @see android.net.EthernetManager
3370 public static final String ETHERNET_SERVICE = "ethernet";
3373 * Use with {@link #getSystemService} to retrieve a {@link
3374 * android.net.nsd.NsdManager} for handling management of network service
3377 * @see #getSystemService
3378 * @see android.net.nsd.NsdManager
3380 public static final String NSD_SERVICE = "servicediscovery";
3383 * Use with {@link #getSystemService} to retrieve a
3384 * {@link android.media.AudioManager} for handling management of volume,
3385 * ringer modes and audio routing.
3387 * @see #getSystemService
3388 * @see android.media.AudioManager
3390 public static final String AUDIO_SERVICE = "audio";
3393 * Use with {@link #getSystemService} to retrieve a
3394 * {@link android.hardware.fingerprint.FingerprintManager} for handling management
3397 * @see #getSystemService
3398 * @see android.hardware.fingerprint.FingerprintManager
3400 public static final String FINGERPRINT_SERVICE = "fingerprint";
3403 * Use with {@link #getSystemService} to retrieve a
3404 * {@link android.media.MediaRouter} for controlling and managing
3407 * @see #getSystemService
3408 * @see android.media.MediaRouter
3410 public static final String MEDIA_ROUTER_SERVICE = "media_router";
3413 * Use with {@link #getSystemService} to retrieve a
3414 * {@link android.media.session.MediaSessionManager} for managing media Sessions.
3416 * @see #getSystemService
3417 * @see android.media.session.MediaSessionManager
3419 public static final String MEDIA_SESSION_SERVICE = "media_session";
3422 * Use with {@link #getSystemService} to retrieve a
3423 * {@link android.telephony.TelephonyManager} for handling management the
3424 * telephony features of the device.
3426 * @see #getSystemService
3427 * @see android.telephony.TelephonyManager
3429 public static final String TELEPHONY_SERVICE = "phone";
3432 * Use with {@link #getSystemService} to retrieve a
3433 * {@link android.telephony.SubscriptionManager} for handling management the
3434 * telephony subscriptions of the device.
3436 * @see #getSystemService
3437 * @see android.telephony.SubscriptionManager
3439 public static final String TELEPHONY_SUBSCRIPTION_SERVICE = "telephony_subscription_service";
3442 * Use with {@link #getSystemService} to retrieve a
3443 * {@link android.telecom.TelecomManager} to manage telecom-related features
3446 * @see #getSystemService
3447 * @see android.telecom.TelecomManager
3449 public static final String TELECOM_SERVICE = "telecom";
3452 * Use with {@link #getSystemService} to retrieve a
3453 * {@link android.telephony.CarrierConfigManager} for reading carrier configuration values.
3455 * @see #getSystemService
3456 * @see android.telephony.CarrierConfigManager
3458 public static final String CARRIER_CONFIG_SERVICE = "carrier_config";
3461 * Use with {@link #getSystemService} to retrieve a
3462 * {@link android.telephony.euicc.EuiccManager} to manage the device eUICC (embedded SIM).
3464 * @see #getSystemService
3465 * @see android.telephony.euicc.EuiccManager
3466 * TODO(b/35851809): Unhide this API.
3469 public static final String EUICC_SERVICE = "euicc_service";
3472 * Use with {@link #getSystemService} to retrieve a
3473 * {@link android.text.ClipboardManager} for accessing and modifying
3474 * {@link android.content.ClipboardManager} for accessing and modifying
3475 * the contents of the global clipboard.
3477 * @see #getSystemService
3478 * @see android.content.ClipboardManager
3480 public static final String CLIPBOARD_SERVICE = "clipboard";
3483 * Use with {@link #getSystemService} to retrieve a
3484 * {@link TextClassificationManager} for text classification services.
3486 * @see #getSystemService
3487 * @see TextClassificationManager
3489 public static final String TEXT_CLASSIFICATION_SERVICE = "textclassification";
3492 * Use with {@link #getSystemService} to retrieve a
3493 * {@link android.view.inputmethod.InputMethodManager} for accessing input
3496 * @see #getSystemService
3498 public static final String INPUT_METHOD_SERVICE = "input_method";
3501 * Use with {@link #getSystemService} to retrieve a
3502 * {@link android.view.textservice.TextServicesManager} for accessing
3505 * @see #getSystemService
3507 public static final String TEXT_SERVICES_MANAGER_SERVICE = "textservices";
3510 * Use with {@link #getSystemService} to retrieve a
3511 * {@link android.appwidget.AppWidgetManager} for accessing AppWidgets.
3513 * @see #getSystemService
3515 public static final String APPWIDGET_SERVICE = "appwidget";
3518 * Official published name of the (internal) voice interaction manager service.
3521 * @see #getSystemService
3523 public static final String VOICE_INTERACTION_MANAGER_SERVICE = "voiceinteraction";
3526 * Official published name of the (internal) autofill service.
3529 * @see #getSystemService
3531 public static final String AUTOFILL_MANAGER_SERVICE = "autofill";
3534 * Use with {@link #getSystemService} to access the
3535 * {@link com.android.server.voiceinteraction.SoundTriggerService}.
3538 * @see #getSystemService
3540 public static final String SOUND_TRIGGER_SERVICE = "soundtrigger";
3544 * Use with {@link #getSystemService} to retrieve an
3545 * {@link android.app.backup.IBackupManager IBackupManager} for communicating
3546 * with the backup mechanism.
3549 * @see #getSystemService
3552 public static final String BACKUP_SERVICE = "backup";
3555 * Use with {@link #getSystemService} to retrieve a
3556 * {@link android.os.DropBoxManager} instance for recording
3558 * @see #getSystemService
3560 public static final String DROPBOX_SERVICE = "dropbox";
3563 * System service name for the DeviceIdleController. There is no Java API for this.
3564 * @see #getSystemService
3567 public static final String DEVICE_IDLE_CONTROLLER = "deviceidle";
3570 * Use with {@link #getSystemService} to retrieve a
3571 * {@link android.app.admin.DevicePolicyManager} for working with global
3572 * device policy management.
3574 * @see #getSystemService
3576 public static final String DEVICE_POLICY_SERVICE = "device_policy";
3579 * Use with {@link #getSystemService} to retrieve a
3580 * {@link android.app.UiModeManager} for controlling UI modes.
3582 * @see #getSystemService
3584 public static final String UI_MODE_SERVICE = "uimode";
3587 * Use with {@link #getSystemService} to retrieve a
3588 * {@link android.app.DownloadManager} for requesting HTTP downloads.
3590 * @see #getSystemService
3592 public static final String DOWNLOAD_SERVICE = "download";
3595 * Use with {@link #getSystemService} to retrieve a
3596 * {@link android.os.BatteryManager} for managing battery state.
3598 * @see #getSystemService
3600 public static final String BATTERY_SERVICE = "batterymanager";
3603 * Use with {@link #getSystemService} to retrieve a
3604 * {@link android.nfc.NfcManager} for using NFC.
3606 * @see #getSystemService
3608 public static final String NFC_SERVICE = "nfc";
3611 * Use with {@link #getSystemService} to retrieve a
3612 * {@link android.bluetooth.BluetoothManager} for using Bluetooth.
3614 * @see #getSystemService
3616 public static final String BLUETOOTH_SERVICE = "bluetooth";
3619 * Use with {@link #getSystemService} to retrieve a
3620 * {@link android.net.sip.SipManager} for accessing the SIP related service.
3622 * @see #getSystemService
3625 public static final String SIP_SERVICE = "sip";
3628 * Use with {@link #getSystemService} to retrieve a {@link
3629 * android.hardware.usb.UsbManager} for access to USB devices (as a USB host)
3630 * and for controlling this device's behavior as a USB device.
3632 * @see #getSystemService
3633 * @see android.hardware.usb.UsbManager
3635 public static final String USB_SERVICE = "usb";
3638 * Use with {@link #getSystemService} to retrieve a {@link
3639 * android.hardware.SerialManager} for access to serial ports.
3641 * @see #getSystemService
3642 * @see android.hardware.SerialManager
3646 public static final String SERIAL_SERVICE = "serial";
3649 * Use with {@link #getSystemService} to retrieve a
3650 * {@link android.hardware.hdmi.HdmiControlManager} for controlling and managing
3651 * HDMI-CEC protocol.
3653 * @see #getSystemService
3654 * @see android.hardware.hdmi.HdmiControlManager
3658 public static final String HDMI_CONTROL_SERVICE = "hdmi_control";
3661 * Use with {@link #getSystemService} to retrieve a
3662 * {@link android.hardware.input.InputManager} for interacting with input devices.
3664 * @see #getSystemService
3665 * @see android.hardware.input.InputManager
3667 public static final String INPUT_SERVICE = "input";
3670 * Use with {@link #getSystemService} to retrieve a
3671 * {@link android.hardware.display.DisplayManager} for interacting with display devices.
3673 * @see #getSystemService
3674 * @see android.hardware.display.DisplayManager
3676 public static final String DISPLAY_SERVICE = "display";
3679 * Use with {@link #getSystemService} to retrieve a
3680 * {@link android.os.UserManager} for managing users on devices that support multiple users.
3682 * @see #getSystemService
3683 * @see android.os.UserManager
3685 public static final String USER_SERVICE = "user";
3688 * Use with {@link #getSystemService} to retrieve a
3689 * {@link android.content.pm.LauncherApps} for querying and monitoring launchable apps across
3690 * profiles of a user.
3692 * @see #getSystemService
3693 * @see android.content.pm.LauncherApps
3695 public static final String LAUNCHER_APPS_SERVICE = "launcherapps";
3698 * Use with {@link #getSystemService} to retrieve a
3699 * {@link android.content.RestrictionsManager} for retrieving application restrictions
3700 * and requesting permissions for restricted operations.
3701 * @see #getSystemService
3702 * @see android.content.RestrictionsManager
3704 public static final String RESTRICTIONS_SERVICE = "restrictions";
3707 * Use with {@link #getSystemService} to retrieve a
3708 * {@link android.app.AppOpsManager} for tracking application operations
3711 * @see #getSystemService
3712 * @see android.app.AppOpsManager
3714 public static final String APP_OPS_SERVICE = "appops";
3717 * Use with {@link #getSystemService} to retrieve a
3718 * {@link android.hardware.camera2.CameraManager} for interacting with
3721 * @see #getSystemService
3722 * @see android.hardware.camera2.CameraManager
3724 public static final String CAMERA_SERVICE = "camera";
3727 * {@link android.print.PrintManager} for printing and managing
3728 * printers and print tasks.
3730 * @see #getSystemService
3731 * @see android.print.PrintManager
3733 public static final String PRINT_SERVICE = "print";
3736 * Use with {@link #getSystemService} to retrieve a
3737 * {@link android.companion.CompanionDeviceManager} for managing companion devices
3739 * @see #getSystemService
3740 * @see android.companion.CompanionDeviceManager
3742 public static final String COMPANION_DEVICE_SERVICE = "companion_device";
3745 * Use with {@link #getSystemService} to retrieve a
3746 * {@link android.hardware.ConsumerIrManager} for transmitting infrared
3747 * signals from the device.
3749 * @see #getSystemService
3750 * @see android.hardware.ConsumerIrManager
3752 public static final String CONSUMER_IR_SERVICE = "consumer_ir";
3755 * {@link android.app.trust.TrustManager} for managing trust agents.
3756 * @see #getSystemService
3757 * @see android.app.trust.TrustManager
3760 public static final String TRUST_SERVICE = "trust";
3763 * Use with {@link #getSystemService} to retrieve a
3764 * {@link android.media.tv.TvInputManager} for interacting with TV inputs
3767 * @see #getSystemService
3768 * @see android.media.tv.TvInputManager
3770 public static final String TV_INPUT_SERVICE = "tv_input";
3773 * {@link android.net.NetworkScoreManager} for managing network scoring.
3774 * @see #getSystemService
3775 * @see android.net.NetworkScoreManager
3779 public static final String NETWORK_SCORE_SERVICE = "network_score";
3782 * Use with {@link #getSystemService} to retrieve a {@link
3783 * android.app.usage.UsageStatsManager} for querying device usage stats.
3785 * @see #getSystemService
3786 * @see android.app.usage.UsageStatsManager
3788 public static final String USAGE_STATS_SERVICE = "usagestats";
3791 * Use with {@link #getSystemService} to retrieve a {@link
3792 * android.app.job.JobScheduler} instance for managing occasional
3794 * @see #getSystemService
3795 * @see android.app.job.JobScheduler
3797 public static final String JOB_SCHEDULER_SERVICE = "jobscheduler";
3800 * Use with {@link #getSystemService} to retrieve a {@link
3801 * android.service.persistentdata.PersistentDataBlockManager} instance
3802 * for interacting with a storage device that lives across factory resets.
3804 * @see #getSystemService
3805 * @see android.service.persistentdata.PersistentDataBlockManager
3809 public static final String PERSISTENT_DATA_BLOCK_SERVICE = "persistent_data_block";
3812 * Use with {@link #getSystemService} to retrieve a {@link
3813 * android.service.oemlock.OemLockManager} instance for managing the OEM lock.
3815 * @see #getSystemService
3816 * @see android.service.oemlock.OemLockManager
3820 public static final String OEM_LOCK_SERVICE = "oem_lock";
3823 * Use with {@link #getSystemService} to retrieve a {@link
3824 * android.media.projection.MediaProjectionManager} instance for managing
3825 * media projection sessions.
3826 * @see #getSystemService
3827 * @see android.media.projection.MediaProjectionManager
3829 public static final String MEDIA_PROJECTION_SERVICE = "media_projection";
3832 * Use with {@link #getSystemService} to retrieve a
3833 * {@link android.media.midi.MidiManager} for accessing the MIDI service.
3835 * @see #getSystemService
3837 public static final String MIDI_SERVICE = "midi";
3841 * Use with {@link #getSystemService} to retrieve a
3842 * {@link android.hardware.radio.RadioManager} for accessing the broadcast radio service.
3844 * @see #getSystemService
3847 public static final String RADIO_SERVICE = "radio";
3850 * Use with {@link #getSystemService} to retrieve a
3851 * {@link android.os.HardwarePropertiesManager} for accessing the hardware properties service.
3853 * @see #getSystemService
3855 public static final String HARDWARE_PROPERTIES_SERVICE = "hardware_properties";
3858 * Use with {@link #getSystemService} to retrieve a
3859 * {@link android.content.pm.ShortcutManager} for accessing the launcher shortcut service.
3861 * @see #getSystemService
3862 * @see android.content.pm.ShortcutManager
3864 public static final String SHORTCUT_SERVICE = "shortcut";
3867 * Use with {@link #getSystemService} to retrieve a {@link
3868 * android.hardware.location.ContextHubManager} for accessing context hubs.
3870 * @see #getSystemService
3871 * @see android.hardware.location.ContextHubManager
3876 public static final String CONTEXTHUB_SERVICE = "contexthub";
3879 * Use with {@link #getSystemService} to retrieve a
3880 * {@link android.os.health.SystemHealthManager} for accessing system health (battery, power,
3881 * memory, etc) metrics.
3883 * @see #getSystemService
3885 public static final String SYSTEM_HEALTH_SERVICE = "systemhealth";
3888 * Gatekeeper Service.
3891 public static final String GATEKEEPER_SERVICE = "android.service.gatekeeper.IGateKeeperService";
3894 * Service defining the policy for access to device identifiers.
3897 public static final String DEVICE_IDENTIFIERS_SERVICE = "device_identifiers";
3900 * Service to report a system health "incident"
3903 public static final String INCIDENT_SERVICE = "incident";
3906 * Use with {@link #getSystemService} to retrieve a {@link
3907 * android.content.om.OverlayManager} for managing overlay packages.
3909 * @see #getSystemService
3910 * @see android.content.om.OverlayManager
3913 public static final String OVERLAY_SERVICE = "overlay";
3916 * Use with {@link #getSystemService} to retrieve a
3917 * {@link VrManager} for accessing the VR service.
3919 * @see #getSystemService
3923 public static final String VR_SERVICE = "vrmanager";
3926 * Determine whether the given permission is allowed for a particular
3927 * process and user ID running in the system.
3929 * @param permission The name of the permission being checked.
3930 * @param pid The process ID being checked against. Must be > 0.
3931 * @param uid The user ID being checked against. A uid of 0 is the root
3932 * user, which will pass every permission check.
3934 * @return {@link PackageManager#PERMISSION_GRANTED} if the given
3935 * pid/uid is allowed that permission, or
3936 * {@link PackageManager#PERMISSION_DENIED} if it is not.
3938 * @see PackageManager#checkPermission(String, String)
3939 * @see #checkCallingPermission
3941 @CheckResult(suggest="#enforcePermission(String,int,int,String)")
3942 @PackageManager.PermissionResult
3943 public abstract int checkPermission(@NonNull String permission, int pid, int uid);
3946 @PackageManager.PermissionResult
3947 public abstract int checkPermission(@NonNull String permission, int pid, int uid,
3948 IBinder callerToken);
3951 * Determine whether the calling process of an IPC you are handling has been
3952 * granted a particular permission. This is basically the same as calling
3953 * {@link #checkPermission(String, int, int)} with the pid and uid returned
3954 * by {@link android.os.Binder#getCallingPid} and
3955 * {@link android.os.Binder#getCallingUid}. One important difference
3956 * is that if you are not currently processing an IPC, this function
3957 * will always fail. This is done to protect against accidentally
3958 * leaking permissions; you can use {@link #checkCallingOrSelfPermission}
3959 * to avoid this protection.
3961 * @param permission The name of the permission being checked.
3963 * @return {@link PackageManager#PERMISSION_GRANTED} if the calling
3964 * pid/uid is allowed that permission, or
3965 * {@link PackageManager#PERMISSION_DENIED} if it is not.
3967 * @see PackageManager#checkPermission(String, String)
3968 * @see #checkPermission
3969 * @see #checkCallingOrSelfPermission
3971 @CheckResult(suggest="#enforceCallingPermission(String,String)")
3972 @PackageManager.PermissionResult
3973 public abstract int checkCallingPermission(@NonNull String permission);
3976 * Determine whether the calling process of an IPC <em>or you</em> have been
3977 * granted a particular permission. This is the same as
3978 * {@link #checkCallingPermission}, except it grants your own permissions
3979 * if you are not currently processing an IPC. Use with care!
3981 * @param permission The name of the permission being checked.
3983 * @return {@link PackageManager#PERMISSION_GRANTED} if the calling
3984 * pid/uid is allowed that permission, or
3985 * {@link PackageManager#PERMISSION_DENIED} if it is not.
3987 * @see PackageManager#checkPermission(String, String)
3988 * @see #checkPermission
3989 * @see #checkCallingPermission
3991 @CheckResult(suggest="#enforceCallingOrSelfPermission(String,String)")
3992 @PackageManager.PermissionResult
3993 public abstract int checkCallingOrSelfPermission(@NonNull String permission);
3996 * Determine whether <em>you</em> have been granted a particular permission.
3998 * @param permission The name of the permission being checked.
4000 * @return {@link PackageManager#PERMISSION_GRANTED} if you have the
4001 * permission, or {@link PackageManager#PERMISSION_DENIED} if not.
4003 * @see PackageManager#checkPermission(String, String)
4004 * @see #checkCallingPermission(String)
4006 @PackageManager.PermissionResult
4007 public abstract int checkSelfPermission(@NonNull String permission);
4010 * If the given permission is not allowed for a particular process
4011 * and user ID running in the system, throw a {@link SecurityException}.
4013 * @param permission The name of the permission being checked.
4014 * @param pid The process ID being checked against. Must be > 0.
4015 * @param uid The user ID being checked against. A uid of 0 is the root
4016 * user, which will pass every permission check.
4017 * @param message A message to include in the exception if it is thrown.
4019 * @see #checkPermission(String, int, int)
4021 public abstract void enforcePermission(
4022 @NonNull String permission, int pid, int uid, @Nullable String message);
4025 * If the calling process of an IPC you are handling has not been
4026 * granted a particular permission, throw a {@link
4027 * SecurityException}. This is basically the same as calling
4028 * {@link #enforcePermission(String, int, int, String)} with the
4029 * pid and uid returned by {@link android.os.Binder#getCallingPid}
4030 * and {@link android.os.Binder#getCallingUid}. One important
4031 * difference is that if you are not currently processing an IPC,
4032 * this function will always throw the SecurityException. This is
4033 * done to protect against accidentally leaking permissions; you
4034 * can use {@link #enforceCallingOrSelfPermission} to avoid this
4037 * @param permission The name of the permission being checked.
4038 * @param message A message to include in the exception if it is thrown.
4040 * @see #checkCallingPermission(String)
4042 public abstract void enforceCallingPermission(
4043 @NonNull String permission, @Nullable String message);
4046 * If neither you nor the calling process of an IPC you are
4047 * handling has been granted a particular permission, throw a
4048 * {@link SecurityException}. This is the same as {@link
4049 * #enforceCallingPermission}, except it grants your own
4050 * permissions if you are not currently processing an IPC. Use
4053 * @param permission The name of the permission being checked.
4054 * @param message A message to include in the exception if it is thrown.
4056 * @see #checkCallingOrSelfPermission(String)
4058 public abstract void enforceCallingOrSelfPermission(
4059 @NonNull String permission, @Nullable String message);
4062 * Grant permission to access a specific Uri to another package, regardless
4063 * of whether that package has general permission to access the Uri's
4064 * content provider. This can be used to grant specific, temporary
4065 * permissions, typically in response to user interaction (such as the
4066 * user opening an attachment that you would like someone else to
4069 * <p>Normally you should use {@link Intent#FLAG_GRANT_READ_URI_PERMISSION
4070 * Intent.FLAG_GRANT_READ_URI_PERMISSION} or
4071 * {@link Intent#FLAG_GRANT_WRITE_URI_PERMISSION
4072 * Intent.FLAG_GRANT_WRITE_URI_PERMISSION} with the Intent being used to
4073 * start an activity instead of this function directly. If you use this
4074 * function directly, you should be sure to call
4075 * {@link #revokeUriPermission} when the target should no longer be allowed
4078 * <p>To succeed, the content provider owning the Uri must have set the
4079 * {@link android.R.styleable#AndroidManifestProvider_grantUriPermissions
4080 * grantUriPermissions} attribute in its manifest or included the
4081 * {@link android.R.styleable#AndroidManifestGrantUriPermission
4082 * <grant-uri-permissions>} tag.
4084 * @param toPackage The package you would like to allow to access the Uri.
4085 * @param uri The Uri you would like to grant access to.
4086 * @param modeFlags The desired access modes. Any combination of
4087 * {@link Intent#FLAG_GRANT_READ_URI_PERMISSION
4088 * Intent.FLAG_GRANT_READ_URI_PERMISSION},
4089 * {@link Intent#FLAG_GRANT_WRITE_URI_PERMISSION
4090 * Intent.FLAG_GRANT_WRITE_URI_PERMISSION},
4091 * {@link Intent#FLAG_GRANT_PERSISTABLE_URI_PERMISSION
4092 * Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION}, or
4093 * {@link Intent#FLAG_GRANT_PREFIX_URI_PERMISSION
4094 * Intent.FLAG_GRANT_PREFIX_URI_PERMISSION}.
4096 * @see #revokeUriPermission
4098 public abstract void grantUriPermission(String toPackage, Uri uri,
4099 @Intent.GrantUriMode int modeFlags);
4102 * Remove all permissions to access a particular content provider Uri
4103 * that were previously added with {@link #grantUriPermission} or <em>any other</em> mechanism.
4104 * The given Uri will match all previously granted Uris that are the same or a
4105 * sub-path of the given Uri. That is, revoking "content://foo/target" will
4106 * revoke both "content://foo/target" and "content://foo/target/sub", but not
4107 * "content://foo". It will not remove any prefix grants that exist at a
4110 * <p>Prior to {@link android.os.Build.VERSION_CODES#LOLLIPOP}, if you did not have
4111 * regular permission access to a Uri, but had received access to it through
4112 * a specific Uri permission grant, you could not revoke that grant with this
4113 * function and a {@link SecurityException} would be thrown. As of
4114 * {@link android.os.Build.VERSION_CODES#LOLLIPOP}, this function will not throw a security
4115 * exception, but will remove whatever permission grants to the Uri had been given to the app
4118 * <p>Unlike {@link #revokeUriPermission(String, Uri, int)}, this method impacts all permission
4119 * grants matching the given Uri, for any package they had been granted to, through any
4120 * mechanism this had happened (such as indirectly through the clipboard, activity launch,
4121 * service start, etc). That means this can be potentially dangerous to use, as it can
4122 * revoke grants that another app could be strongly expecting to stick around.</p>
4124 * @param uri The Uri you would like to revoke access to.
4125 * @param modeFlags The desired access modes. Any combination of
4126 * {@link Intent#FLAG_GRANT_READ_URI_PERMISSION
4127 * Intent.FLAG_GRANT_READ_URI_PERMISSION} or
4128 * {@link Intent#FLAG_GRANT_WRITE_URI_PERMISSION
4129 * Intent.FLAG_GRANT_WRITE_URI_PERMISSION}.
4131 * @see #grantUriPermission
4133 public abstract void revokeUriPermission(Uri uri, @Intent.AccessUriMode int modeFlags);
4136 * Remove permissions to access a particular content provider Uri
4137 * that were previously added with {@link #grantUriPermission} for a specific target
4138 * package. The given Uri will match all previously granted Uris that are the same or a
4139 * sub-path of the given Uri. That is, revoking "content://foo/target" will
4140 * revoke both "content://foo/target" and "content://foo/target/sub", but not
4141 * "content://foo". It will not remove any prefix grants that exist at a
4144 * <p>Unlike {@link #revokeUriPermission(Uri, int)}, this method will <em>only</em>
4145 * revoke permissions that had been explicitly granted through {@link #grantUriPermission}
4146 * and only for the package specified. Any matching grants that have happened through
4147 * other mechanisms (clipboard, activity launching, service starting, etc) will not be
4150 * @param toPackage The package you had previously granted access to.
4151 * @param uri The Uri you would like to revoke access to.
4152 * @param modeFlags The desired access modes. Any combination of
4153 * {@link Intent#FLAG_GRANT_READ_URI_PERMISSION
4154 * Intent.FLAG_GRANT_READ_URI_PERMISSION} or
4155 * {@link Intent#FLAG_GRANT_WRITE_URI_PERMISSION
4156 * Intent.FLAG_GRANT_WRITE_URI_PERMISSION}.
4158 * @see #grantUriPermission
4160 public abstract void revokeUriPermission(String toPackage, Uri uri,
4161 @Intent.AccessUriMode int modeFlags);
4164 * Determine whether a particular process and user ID has been granted
4165 * permission to access a specific URI. This only checks for permissions
4166 * that have been explicitly granted -- if the given process/uid has
4167 * more general access to the URI's content provider then this check will
4170 * @param uri The uri that is being checked.
4171 * @param pid The process ID being checked against. Must be > 0.
4172 * @param uid The user ID being checked against. A uid of 0 is the root
4173 * user, which will pass every permission check.
4174 * @param modeFlags The type of access to grant. May be one or both of
4175 * {@link Intent#FLAG_GRANT_READ_URI_PERMISSION Intent.FLAG_GRANT_READ_URI_PERMISSION} or
4176 * {@link Intent#FLAG_GRANT_WRITE_URI_PERMISSION Intent.FLAG_GRANT_WRITE_URI_PERMISSION}.
4178 * @return {@link PackageManager#PERMISSION_GRANTED} if the given
4179 * pid/uid is allowed to access that uri, or
4180 * {@link PackageManager#PERMISSION_DENIED} if it is not.
4182 * @see #checkCallingUriPermission
4184 @CheckResult(suggest="#enforceUriPermission(Uri,int,int,String)")
4185 public abstract int checkUriPermission(Uri uri, int pid, int uid,
4186 @Intent.AccessUriMode int modeFlags);
4189 public abstract int checkUriPermission(Uri uri, int pid, int uid,
4190 @Intent.AccessUriMode int modeFlags, IBinder callerToken);
4193 * Determine whether the calling process and user ID has been
4194 * granted permission to access a specific URI. This is basically
4195 * the same as calling {@link #checkUriPermission(Uri, int, int,
4196 * int)} with the pid and uid returned by {@link
4197 * android.os.Binder#getCallingPid} and {@link
4198 * android.os.Binder#getCallingUid}. One important difference is
4199 * that if you are not currently processing an IPC, this function
4202 * @param uri The uri that is being checked.
4203 * @param modeFlags The type of access to grant. May be one or both of
4204 * {@link Intent#FLAG_GRANT_READ_URI_PERMISSION Intent.FLAG_GRANT_READ_URI_PERMISSION} or
4205 * {@link Intent#FLAG_GRANT_WRITE_URI_PERMISSION Intent.FLAG_GRANT_WRITE_URI_PERMISSION}.
4207 * @return {@link PackageManager#PERMISSION_GRANTED} if the caller
4208 * is allowed to access that uri, or
4209 * {@link PackageManager#PERMISSION_DENIED} if it is not.
4211 * @see #checkUriPermission(Uri, int, int, int)
4213 @CheckResult(suggest="#enforceCallingUriPermission(Uri,int,String)")
4214 public abstract int checkCallingUriPermission(Uri uri, @Intent.AccessUriMode int modeFlags);
4217 * Determine whether the calling process of an IPC <em>or you</em> has been granted
4218 * permission to access a specific URI. This is the same as
4219 * {@link #checkCallingUriPermission}, except it grants your own permissions
4220 * if you are not currently processing an IPC. Use with care!
4222 * @param uri The uri that is being checked.
4223 * @param modeFlags The type of access to grant. May be one or both of
4224 * {@link Intent#FLAG_GRANT_READ_URI_PERMISSION Intent.FLAG_GRANT_READ_URI_PERMISSION} or
4225 * {@link Intent#FLAG_GRANT_WRITE_URI_PERMISSION Intent.FLAG_GRANT_WRITE_URI_PERMISSION}.
4227 * @return {@link PackageManager#PERMISSION_GRANTED} if the caller
4228 * is allowed to access that uri, or
4229 * {@link PackageManager#PERMISSION_DENIED} if it is not.
4231 * @see #checkCallingUriPermission
4233 @CheckResult(suggest="#enforceCallingOrSelfUriPermission(Uri,int,String)")
4234 public abstract int checkCallingOrSelfUriPermission(Uri uri,
4235 @Intent.AccessUriMode int modeFlags);
4238 * Check both a Uri and normal permission. This allows you to perform
4239 * both {@link #checkPermission} and {@link #checkUriPermission} in one
4242 * @param uri The Uri whose permission is to be checked, or null to not
4244 * @param readPermission The permission that provides overall read access,
4245 * or null to not do this check.
4246 * @param writePermission The permission that provides overall write
4247 * access, or null to not do this check.
4248 * @param pid The process ID being checked against. Must be > 0.
4249 * @param uid The user ID being checked against. A uid of 0 is the root
4250 * user, which will pass every permission check.
4251 * @param modeFlags The type of access to grant. May be one or both of
4252 * {@link Intent#FLAG_GRANT_READ_URI_PERMISSION Intent.FLAG_GRANT_READ_URI_PERMISSION} or
4253 * {@link Intent#FLAG_GRANT_WRITE_URI_PERMISSION Intent.FLAG_GRANT_WRITE_URI_PERMISSION}.
4255 * @return {@link PackageManager#PERMISSION_GRANTED} if the caller
4256 * is allowed to access that uri or holds one of the given permissions, or
4257 * {@link PackageManager#PERMISSION_DENIED} if it is not.
4259 @CheckResult(suggest="#enforceUriPermission(Uri,String,String,int,int,int,String)")
4260 public abstract int checkUriPermission(@Nullable Uri uri, @Nullable String readPermission,
4261 @Nullable String writePermission, int pid, int uid,
4262 @Intent.AccessUriMode int modeFlags);
4265 * If a particular process and user ID has not been granted
4266 * permission to access a specific URI, throw {@link
4267 * SecurityException}. This only checks for permissions that have
4268 * been explicitly granted -- if the given process/uid has more
4269 * general access to the URI's content provider then this check
4272 * @param uri The uri that is being checked.
4273 * @param pid The process ID being checked against. Must be > 0.
4274 * @param uid The user ID being checked against. A uid of 0 is the root
4275 * user, which will pass every permission check.
4276 * @param modeFlags The type of access to grant. May be one or both of
4277 * {@link Intent#FLAG_GRANT_READ_URI_PERMISSION Intent.FLAG_GRANT_READ_URI_PERMISSION} or
4278 * {@link Intent#FLAG_GRANT_WRITE_URI_PERMISSION Intent.FLAG_GRANT_WRITE_URI_PERMISSION}.
4279 * @param message A message to include in the exception if it is thrown.
4281 * @see #checkUriPermission(Uri, int, int, int)
4283 public abstract void enforceUriPermission(
4284 Uri uri, int pid, int uid, @Intent.AccessUriMode int modeFlags, String message);
4287 * If the calling process and user ID has not been granted
4288 * permission to access a specific URI, throw {@link
4289 * SecurityException}. This is basically the same as calling
4290 * {@link #enforceUriPermission(Uri, int, int, int, String)} with
4291 * the pid and uid returned by {@link
4292 * android.os.Binder#getCallingPid} and {@link
4293 * android.os.Binder#getCallingUid}. One important difference is
4294 * that if you are not currently processing an IPC, this function
4295 * will always throw a SecurityException.
4297 * @param uri The uri that is being checked.
4298 * @param modeFlags The type of access to grant. May be one or both of
4299 * {@link Intent#FLAG_GRANT_READ_URI_PERMISSION Intent.FLAG_GRANT_READ_URI_PERMISSION} or
4300 * {@link Intent#FLAG_GRANT_WRITE_URI_PERMISSION Intent.FLAG_GRANT_WRITE_URI_PERMISSION}.
4301 * @param message A message to include in the exception if it is thrown.
4303 * @see #checkCallingUriPermission(Uri, int)
4305 public abstract void enforceCallingUriPermission(
4306 Uri uri, @Intent.AccessUriMode int modeFlags, String message);
4309 * If the calling process of an IPC <em>or you</em> has not been
4310 * granted permission to access a specific URI, throw {@link
4311 * SecurityException}. This is the same as {@link
4312 * #enforceCallingUriPermission}, except it grants your own
4313 * permissions if you are not currently processing an IPC. Use
4316 * @param uri The uri that is being checked.
4317 * @param modeFlags The type of access to grant. May be one or both of
4318 * {@link Intent#FLAG_GRANT_READ_URI_PERMISSION Intent.FLAG_GRANT_READ_URI_PERMISSION} or
4319 * {@link Intent#FLAG_GRANT_WRITE_URI_PERMISSION Intent.FLAG_GRANT_WRITE_URI_PERMISSION}.
4320 * @param message A message to include in the exception if it is thrown.
4322 * @see #checkCallingOrSelfUriPermission(Uri, int)
4324 public abstract void enforceCallingOrSelfUriPermission(
4325 Uri uri, @Intent.AccessUriMode int modeFlags, String message);
4328 * Enforce both a Uri and normal permission. This allows you to perform
4329 * both {@link #enforcePermission} and {@link #enforceUriPermission} in one
4332 * @param uri The Uri whose permission is to be checked, or null to not
4334 * @param readPermission The permission that provides overall read access,
4335 * or null to not do this check.
4336 * @param writePermission The permission that provides overall write
4337 * access, or null to not do this check.
4338 * @param pid The process ID being checked against. Must be > 0.
4339 * @param uid The user ID being checked against. A uid of 0 is the root
4340 * user, which will pass every permission check.
4341 * @param modeFlags The type of access to grant. May be one or both of
4342 * {@link Intent#FLAG_GRANT_READ_URI_PERMISSION Intent.FLAG_GRANT_READ_URI_PERMISSION} or
4343 * {@link Intent#FLAG_GRANT_WRITE_URI_PERMISSION Intent.FLAG_GRANT_WRITE_URI_PERMISSION}.
4344 * @param message A message to include in the exception if it is thrown.
4346 * @see #checkUriPermission(Uri, String, String, int, int, int)
4348 public abstract void enforceUriPermission(
4349 @Nullable Uri uri, @Nullable String readPermission,
4350 @Nullable String writePermission, int pid, int uid, @Intent.AccessUriMode int modeFlags,
4351 @Nullable String message);
4354 @IntDef(flag = true,
4355 value = {CONTEXT_INCLUDE_CODE, CONTEXT_IGNORE_SECURITY, CONTEXT_RESTRICTED})
4356 @Retention(RetentionPolicy.SOURCE)
4357 public @interface CreatePackageOptions {}
4360 * Flag for use with {@link #createPackageContext}: include the application
4361 * code with the context. This means loading code into the caller's
4362 * process, so that {@link #getClassLoader()} can be used to instantiate
4363 * the application's classes. Setting this flags imposes security
4364 * restrictions on what application context you can access; if the
4365 * requested application can not be safely loaded into your process,
4366 * java.lang.SecurityException will be thrown. If this flag is not set,
4367 * there will be no restrictions on the packages that can be loaded,
4368 * but {@link #getClassLoader} will always return the default system
4371 public static final int CONTEXT_INCLUDE_CODE = 0x00000001;
4374 * Flag for use with {@link #createPackageContext}: ignore any security
4375 * restrictions on the Context being requested, allowing it to always
4376 * be loaded. For use with {@link #CONTEXT_INCLUDE_CODE} to allow code
4377 * to be loaded into a process even when it isn't safe to do so. Use
4378 * with extreme care!
4380 public static final int CONTEXT_IGNORE_SECURITY = 0x00000002;
4383 * Flag for use with {@link #createPackageContext}: a restricted context may
4384 * disable specific features. For instance, a View associated with a restricted
4385 * context would ignore particular XML attributes.
4387 public static final int CONTEXT_RESTRICTED = 0x00000004;
4390 * Flag for use with {@link #createPackageContext}: point all file APIs at
4391 * device-protected storage.
4395 public static final int CONTEXT_DEVICE_PROTECTED_STORAGE = 0x00000008;
4398 * Flag for use with {@link #createPackageContext}: point all file APIs at
4399 * credential-protected storage.
4403 public static final int CONTEXT_CREDENTIAL_PROTECTED_STORAGE = 0x00000010;
4406 * @hide Used to indicate we should tell the activity manager about the process
4407 * loading this code.
4409 public static final int CONTEXT_REGISTER_PACKAGE = 0x40000000;
4412 * Return a new Context object for the given application name. This
4413 * Context is the same as what the named application gets when it is
4414 * launched, containing the same resources and class loader. Each call to
4415 * this method returns a new instance of a Context object; Context objects
4416 * are not shared, however they share common state (Resources, ClassLoader,
4417 * etc) so the Context instance itself is fairly lightweight.
4419 * <p>Throws {@link android.content.pm.PackageManager.NameNotFoundException} if there is no
4420 * application with the given package name.
4422 * <p>Throws {@link java.lang.SecurityException} if the Context requested
4423 * can not be loaded into the caller's process for security reasons (see
4424 * {@link #CONTEXT_INCLUDE_CODE} for more information}.
4426 * @param packageName Name of the application's package.
4427 * @param flags Option flags, one of {@link #CONTEXT_INCLUDE_CODE}
4428 * or {@link #CONTEXT_IGNORE_SECURITY}.
4430 * @return A {@link Context} for the application.
4432 * @throws SecurityException
4433 * @throws PackageManager.NameNotFoundException if there is no application with
4434 * the given package name.
4436 public abstract Context createPackageContext(String packageName,
4437 @CreatePackageOptions int flags) throws PackageManager.NameNotFoundException;
4440 * Similar to {@link #createPackageContext(String, int)}, but with a
4441 * different {@link UserHandle}. For example, {@link #getContentResolver()}
4442 * will open any {@link Uri} as the given user.
4446 public abstract Context createPackageContextAsUser(
4447 String packageName, int flags, UserHandle user)
4448 throws PackageManager.NameNotFoundException;
4451 * Creates a context given an {@link android.content.pm.ApplicationInfo}.
4455 public abstract Context createApplicationContext(ApplicationInfo application,
4456 int flags) throws PackageManager.NameNotFoundException;
4459 * Return a new Context object for the given split name. The new Context has a ClassLoader and
4460 * Resources object that can access the split's and all of its dependencies' code/resources.
4461 * Each call to this method returns a new instance of a Context object;
4462 * Context objects are not shared, however common state (ClassLoader, other Resources for
4463 * the same split) may be so the Context itself can be fairly lightweight.
4465 * @param splitName The name of the split to include, as declared in the split's
4466 * <code>AndroidManifest.xml</code>.
4467 * @return A {@link Context} with the given split's code and/or resources loaded.
4469 public abstract Context createContextForSplit(String splitName)
4470 throws PackageManager.NameNotFoundException;
4473 * Get the userId associated with this context
4479 public abstract @UserIdInt int getUserId();
4482 * Return a new Context object for the current Context but whose resources
4483 * are adjusted to match the given Configuration. Each call to this method
4484 * returns a new instance of a Context object; Context objects are not
4485 * shared, however common state (ClassLoader, other Resources for the
4486 * same configuration) may be so the Context itself can be fairly lightweight.
4488 * @param overrideConfiguration A {@link Configuration} specifying what
4489 * values to modify in the base Configuration of the original Context's
4490 * resources. If the base configuration changes (such as due to an
4491 * orientation change), the resources of this context will also change except
4492 * for those that have been explicitly overridden with a value here.
4494 * @return A {@link Context} with the given configuration override.
4496 public abstract Context createConfigurationContext(
4497 @NonNull Configuration overrideConfiguration);
4500 * Return a new Context object for the current Context but whose resources
4501 * are adjusted to match the metrics of the given Display. Each call to this method
4502 * returns a new instance of a Context object; Context objects are not
4503 * shared, however common state (ClassLoader, other Resources for the
4504 * same configuration) may be so the Context itself can be fairly lightweight.
4506 * The returned display Context provides a {@link WindowManager}
4507 * (see {@link #getSystemService(String)}) that is configured to show windows
4508 * on the given display. The WindowManager's {@link WindowManager#getDefaultDisplay}
4509 * method can be used to retrieve the Display from the returned Context.
4511 * @param display A {@link Display} object specifying the display
4512 * for whose metrics the Context's resources should be tailored and upon which
4513 * new windows should be shown.
4515 * @return A {@link Context} for the display.
4517 public abstract Context createDisplayContext(@NonNull Display display);
4520 * Return a new Context object for the current Context but whose storage
4521 * APIs are backed by device-protected storage.
4523 * On devices with direct boot, data stored in this location is encrypted
4524 * with a key tied to the physical device, and it can be accessed
4525 * immediately after the device has booted successfully, both
4526 * <em>before and after</em> the user has authenticated with their
4527 * credentials (such as a lock pattern or PIN).
4529 * Because device-protected data is available without user authentication,
4530 * you should carefully limit the data you store using this Context. For
4531 * example, storing sensitive authentication tokens or passwords in the
4532 * device-protected area is strongly discouraged.
4534 * If the underlying device does not have the ability to store
4535 * device-protected and credential-protected data using different keys, then
4536 * both storage areas will become available at the same time. They remain as
4537 * two distinct storage locations on disk, and only the window of
4538 * availability changes.
4540 * Each call to this method returns a new instance of a Context object;
4541 * Context objects are not shared, however common state (ClassLoader, other
4542 * Resources for the same configuration) may be so the Context itself can be
4543 * fairly lightweight.
4545 * @see #isDeviceProtectedStorage()
4547 public abstract Context createDeviceProtectedStorageContext();
4550 * Return a new Context object for the current Context but whose storage
4551 * APIs are backed by credential-protected storage. This is the default
4552 * storage area for apps unless
4553 * {@link android.R.attr#defaultToDeviceProtectedStorage} was requested.
4555 * On devices with direct boot, data stored in this location is encrypted
4556 * with a key tied to user credentials, which can be accessed
4557 * <em>only after</em> the user has entered their credentials (such as a
4558 * lock pattern or PIN).
4560 * If the underlying device does not have the ability to store
4561 * device-protected and credential-protected data using different keys, then
4562 * both storage areas will become available at the same time. They remain as
4563 * two distinct storage locations on disk, and only the window of
4564 * availability changes.
4566 * Each call to this method returns a new instance of a Context object;
4567 * Context objects are not shared, however common state (ClassLoader, other
4568 * Resources for the same configuration) may be so the Context itself can be
4569 * fairly lightweight.
4571 * @see #isCredentialProtectedStorage()
4575 public abstract Context createCredentialProtectedStorageContext();
4578 * Gets the display adjustments holder for this context. This information
4579 * is provided on a per-application or activity basis and is used to simulate lower density
4580 * display metrics for legacy applications and restricted screen sizes.
4582 * @param displayId The display id for which to get compatibility info.
4583 * @return The compatibility info holder, or null if not required by the application.
4586 public abstract DisplayAdjustments getDisplayAdjustments(int displayId);
4591 public abstract Display getDisplay();
4596 public abstract void updateDisplay(int displayId);
4599 * Indicates whether this Context is restricted.
4601 * @return {@code true} if this Context is restricted, {@code false} otherwise.
4603 * @see #CONTEXT_RESTRICTED
4605 public boolean isRestricted() {
4610 * Indicates if the storage APIs of this Context are backed by
4611 * device-protected storage.
4613 * @see #createDeviceProtectedStorageContext()
4615 public abstract boolean isDeviceProtectedStorage();
4618 * Indicates if the storage APIs of this Context are backed by
4619 * credential-protected storage.
4621 * @see #createCredentialProtectedStorageContext()
4625 public abstract boolean isCredentialProtectedStorage();
4630 public IBinder getActivityToken() {
4631 throw new RuntimeException("Not implemented. Must override in a subclass.");
4638 public IServiceConnection getServiceDispatcher(ServiceConnection conn, Handler handler,
4640 throw new RuntimeException("Not implemented. Must override in a subclass.");
4646 public IApplicationThread getIApplicationThread() {
4647 throw new RuntimeException("Not implemented. Must override in a subclass.");
4653 public Handler getMainThreadHandler() {
4654 throw new RuntimeException("Not implemented. Must override in a subclass.");
4658 * Throws an exception if the Context is using system resources,
4659 * which are non-runtime-overlay-themable and may show inconsistent UI.
4662 public void assertRuntimeOverlayThemable() {
4663 // Resources.getSystem() is a singleton and the only Resources not managed by
4664 // ResourcesManager; therefore Resources.getSystem() is not themable.
4665 if (getResources() == Resources.getSystem()) {
4666 throw new IllegalArgumentException("Non-UI context used to display UI; "
4667 + "get a UI context from ActivityThread#getSystemUiContext()");