1 /*
2  * Copyright (C) 2006 The Android Open Source Project
3  *
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
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
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.
15  */
16 
17 package android.content;
18 
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.ActivityManager;
36 import android.app.IApplicationThread;
37 import android.app.IServiceConnection;
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.Build;
53 import android.os.Bundle;
54 import android.os.Environment;
55 import android.os.Handler;
56 import android.os.HandlerExecutor;
57 import android.os.IBinder;
58 import android.os.Looper;
59 import android.os.StatFs;
60 import android.os.UserHandle;
61 import android.os.UserManager;
62 import android.os.storage.StorageManager;
63 import android.provider.MediaStore;
64 import android.util.AttributeSet;
65 import android.view.Display;
66 import android.view.DisplayAdjustments;
67 import android.view.View;
68 import android.view.ViewDebug;
69 import android.view.WindowManager;
70 import android.view.autofill.AutofillManager.AutofillClient;
71 import android.view.textclassifier.TextClassificationManager;
72 
73 import java.io.File;
74 import java.io.FileInputStream;
75 import java.io.FileNotFoundException;
76 import java.io.FileOutputStream;
77 import java.io.IOException;
78 import java.io.InputStream;
79 import java.lang.annotation.Retention;
80 import java.lang.annotation.RetentionPolicy;
81 import java.util.concurrent.Executor;
82 
83 /**
84  * Interface to global information about an application environment.  This is
85  * an abstract class whose implementation is provided by
86  * the Android system.  It
87  * allows access to application-specific resources and classes, as well as
88  * up-calls for application-level operations such as launching activities,
89  * broadcasting and receiving intents, etc.
90  */
91 public abstract class Context {
92     /** @hide */
93     @IntDef(flag = true, prefix = { "MODE_" }, value = {
94             MODE_PRIVATE,
95             MODE_WORLD_READABLE,
96             MODE_WORLD_WRITEABLE,
97             MODE_APPEND,
98     })
99     @Retention(RetentionPolicy.SOURCE)
100     public @interface FileMode {}
101 
102     /** @hide */
103     @IntDef(flag = true, prefix = { "MODE_" }, value = {
104             MODE_PRIVATE,
105             MODE_WORLD_READABLE,
106             MODE_WORLD_WRITEABLE,
107             MODE_MULTI_PROCESS,
108     })
109     @Retention(RetentionPolicy.SOURCE)
110     public @interface PreferencesMode {}
111 
112     /** @hide */
113     @IntDef(flag = true, prefix = { "MODE_" }, value = {
114             MODE_PRIVATE,
115             MODE_WORLD_READABLE,
116             MODE_WORLD_WRITEABLE,
117             MODE_ENABLE_WRITE_AHEAD_LOGGING,
118             MODE_NO_LOCALIZED_COLLATORS,
119     })
120     @Retention(RetentionPolicy.SOURCE)
121     public @interface DatabaseMode {}
122 
123     /**
124      * File creation mode: the default mode, where the created file can only
125      * be accessed by the calling application (or all applications sharing the
126      * same user ID).
127      */
128     public static final int MODE_PRIVATE = 0x0000;
129 
130     /**
131      * File creation mode: allow all other applications to have read access to
132      * the created file.
133      * <p>
134      * Starting from {@link android.os.Build.VERSION_CODES#N}, attempting to use this
135      * mode throws a {@link SecurityException}.
136      *
137      * @deprecated Creating world-readable files is very dangerous, and likely
138      *             to cause security holes in applications. It is strongly
139      *             discouraged; instead, applications should use more formal
140      *             mechanism for interactions such as {@link ContentProvider},
141      *             {@link BroadcastReceiver}, and {@link android.app.Service}.
142      *             There are no guarantees that this access mode will remain on
143      *             a file, such as when it goes through a backup and restore.
144      * @see android.support.v4.content.FileProvider
145      * @see Intent#FLAG_GRANT_WRITE_URI_PERMISSION
146      */
147     @Deprecated
148     public static final int MODE_WORLD_READABLE = 0x0001;
149 
150     /**
151      * File creation mode: allow all other applications to have write access to
152      * the created file.
153      * <p>
154      * Starting from {@link android.os.Build.VERSION_CODES#N}, attempting to use this
155      * mode will throw a {@link SecurityException}.
156      *
157      * @deprecated Creating world-writable files is very dangerous, and likely
158      *             to cause security holes in applications. It is strongly
159      *             discouraged; instead, applications should use more formal
160      *             mechanism for interactions such as {@link ContentProvider},
161      *             {@link BroadcastReceiver}, and {@link android.app.Service}.
162      *             There are no guarantees that this access mode will remain on
163      *             a file, such as when it goes through a backup and restore.
164      * @see android.support.v4.content.FileProvider
165      * @see Intent#FLAG_GRANT_WRITE_URI_PERMISSION
166      */
167     @Deprecated
168     public static final int MODE_WORLD_WRITEABLE = 0x0002;
169 
170     /**
171      * File creation mode: for use with {@link #openFileOutput}, if the file
172      * already exists then write data to the end of the existing file
173      * instead of erasing it.
174      * @see #openFileOutput
175      */
176     public static final int MODE_APPEND = 0x8000;
177 
178     /**
179      * SharedPreference loading flag: when set, the file on disk will
180      * be checked for modification even if the shared preferences
181      * instance is already loaded in this process.  This behavior is
182      * sometimes desired in cases where the application has multiple
183      * processes, all writing to the same SharedPreferences file.
184      * Generally there are better forms of communication between
185      * processes, though.
186      *
187      * <p>This was the legacy (but undocumented) behavior in and
188      * before Gingerbread (Android 2.3) and this flag is implied when
189      * targetting such releases.  For applications targetting SDK
190      * versions <em>greater than</em> Android 2.3, this flag must be
191      * explicitly set if desired.
192      *
193      * @see #getSharedPreferences
194      *
195      * @deprecated MODE_MULTI_PROCESS does not work reliably in
196      * some versions of Android, and furthermore does not provide any
197      * mechanism for reconciling concurrent modifications across
198      * processes.  Applications should not attempt to use it.  Instead,
199      * they should use an explicit cross-process data management
200      * approach such as {@link android.content.ContentProvider ContentProvider}.
201      */
202     @Deprecated
203     public static final int MODE_MULTI_PROCESS = 0x0004;
204 
205     /**
206      * Database open flag: when set, the database is opened with write-ahead
207      * logging enabled by default.
208      *
209      * @see #openOrCreateDatabase(String, int, CursorFactory)
210      * @see #openOrCreateDatabase(String, int, CursorFactory, DatabaseErrorHandler)
211      * @see SQLiteDatabase#enableWriteAheadLogging
212      */
213     public static final int MODE_ENABLE_WRITE_AHEAD_LOGGING = 0x0008;
214 
215     /**
216      * Database open flag: when set, the database is opened without support for
217      * localized collators.
218      *
219      * @see #openOrCreateDatabase(String, int, CursorFactory)
220      * @see #openOrCreateDatabase(String, int, CursorFactory, DatabaseErrorHandler)
221      * @see SQLiteDatabase#NO_LOCALIZED_COLLATORS
222      */
223     public static final int MODE_NO_LOCALIZED_COLLATORS = 0x0010;
224 
225     /** @hide */
226     @IntDef(flag = true, prefix = { "BIND_" }, value = {
227             BIND_AUTO_CREATE,
228             BIND_DEBUG_UNBIND,
229             BIND_NOT_FOREGROUND,
230             BIND_ABOVE_CLIENT,
231             BIND_ALLOW_OOM_MANAGEMENT,
232             BIND_WAIVE_PRIORITY,
233             BIND_IMPORTANT,
234             BIND_ADJUST_WITH_ACTIVITY
235     })
236     @Retention(RetentionPolicy.SOURCE)
237     public @interface BindServiceFlags {}
238 
239     /**
240      * Flag for {@link #bindService}: automatically create the service as long
241      * as the binding exists.  Note that while this will create the service,
242      * its {@link android.app.Service#onStartCommand}
243      * method will still only be called due to an
244      * explicit call to {@link #startService}.  Even without that, though,
245      * this still provides you with access to the service object while the
246      * service is created.
247      *
248      * <p>Note that prior to {@link android.os.Build.VERSION_CODES#ICE_CREAM_SANDWICH},
249      * not supplying this flag would also impact how important the system
250      * consider's the target service's process to be.  When set, the only way
251      * for it to be raised was by binding from a service in which case it will
252      * only be important when that activity is in the foreground.  Now to
253      * achieve this behavior you must explicitly supply the new flag
254      * {@link #BIND_ADJUST_WITH_ACTIVITY}.  For compatibility, old applications
255      * that don't specify {@link #BIND_AUTO_CREATE} will automatically have
256      * the flags {@link #BIND_WAIVE_PRIORITY} and
257      * {@link #BIND_ADJUST_WITH_ACTIVITY} set for them in order to achieve
258      * the same result.
259      */
260     public static final int BIND_AUTO_CREATE = 0x0001;
261 
262     /**
263      * Flag for {@link #bindService}: include debugging help for mismatched
264      * calls to unbind.  When this flag is set, the callstack of the following
265      * {@link #unbindService} call is retained, to be printed if a later
266      * incorrect unbind call is made.  Note that doing this requires retaining
267      * information about the binding that was made for the lifetime of the app,
268      * resulting in a leak -- this should only be used for debugging.
269      */
270     public static final int BIND_DEBUG_UNBIND = 0x0002;
271 
272     /**
273      * Flag for {@link #bindService}: don't allow this binding to raise
274      * the target service's process to the foreground scheduling priority.
275      * It will still be raised to at least the same memory priority
276      * as the client (so that its process will not be killable in any
277      * situation where the client is not killable), but for CPU scheduling
278      * purposes it may be left in the background.  This only has an impact
279      * in the situation where the binding client is a foreground process
280      * and the target service is in a background process.
281      */
282     public static final int BIND_NOT_FOREGROUND = 0x0004;
283 
284     /**
285      * Flag for {@link #bindService}: indicates that the client application
286      * binding to this service considers the service to be more important than
287      * the app itself.  When set, the platform will try to have the out of
288      * memory killer kill the app before it kills the service it is bound to, though
289      * this is not guaranteed to be the case.
290      */
291     public static final int BIND_ABOVE_CLIENT = 0x0008;
292 
293     /**
294      * Flag for {@link #bindService}: allow the process hosting the bound
295      * service to go through its normal memory management.  It will be
296      * treated more like a running service, allowing the system to
297      * (temporarily) expunge the process if low on memory or for some other
298      * whim it may have, and being more aggressive about making it a candidate
299      * to be killed (and restarted) if running for a long time.
300      */
301     public static final int BIND_ALLOW_OOM_MANAGEMENT = 0x0010;
302 
303     /**
304      * Flag for {@link #bindService}: don't impact the scheduling or
305      * memory management priority of the target service's hosting process.
306      * Allows the service's process to be managed on the background LRU list
307      * just like a regular application process in the background.
308      */
309     public static final int BIND_WAIVE_PRIORITY = 0x0020;
310 
311     /**
312      * Flag for {@link #bindService}: this service is very important to
313      * the client, so should be brought to the foreground process level
314      * when the client is.  Normally a process can only be raised to the
315      * visibility level by a client, even if that client is in the foreground.
316      */
317     public static final int BIND_IMPORTANT = 0x0040;
318 
319     /**
320      * Flag for {@link #bindService}: If binding from an activity, allow the
321      * target service's process importance to be raised based on whether the
322      * activity is visible to the user, regardless whether another flag is
323      * used to reduce the amount that the client process's overall importance
324      * is used to impact it.
325      */
326     public static final int BIND_ADJUST_WITH_ACTIVITY = 0x0080;
327 
328     /**
329      * @hide Flag for {@link #bindService}: allows binding to a service provided
330      * by an instant app. Note that the caller may not have access to the instant
331      * app providing the service which is a violation of the instant app sandbox.
332      * This flag is intended ONLY for development/testing and should be used with
333      * great care. Only the system is allowed to use this flag.
334      */
335     public static final int BIND_ALLOW_INSTANT = 0x00400000;
336 
337     /**
338      * @hide Flag for {@link #bindService}: like {@link #BIND_NOT_FOREGROUND}, but puts it
339      * up in to the important background state (instead of transient).
340      */
341     public static final int BIND_IMPORTANT_BACKGROUND = 0x00800000;
342 
343     /**
344      * @hide Flag for {@link #bindService}: allows application hosting service to manage whitelists
345      * such as temporary allowing a {@code PendingIntent} to bypass Power Save mode.
346      */
347     public static final int BIND_ALLOW_WHITELIST_MANAGEMENT = 0x01000000;
348 
349     /**
350      * @hide Flag for {@link #bindService}: Like {@link #BIND_FOREGROUND_SERVICE},
351      * but only applies while the device is awake.
352      */
353     public static final int BIND_FOREGROUND_SERVICE_WHILE_AWAKE = 0x02000000;
354 
355     /**
356      * @hide Flag for {@link #bindService}: For only the case where the binding
357      * is coming from the system, set the process state to FOREGROUND_SERVICE
358      * instead of the normal maximum of IMPORTANT_FOREGROUND.  That is, this is
359      * saying that the process shouldn't participate in the normal power reduction
360      * modes (removing network access etc).
361      */
362     public static final int BIND_FOREGROUND_SERVICE = 0x04000000;
363 
364     /**
365      * @hide Flag for {@link #bindService}: Treat the binding as hosting
366      * an activity, an unbinding as the activity going in the background.
367      * That is, when unbinding, the process when empty will go on the activity
368      * LRU list instead of the regular one, keeping it around more aggressively
369      * than it otherwise would be.  This is intended for use with IMEs to try
370      * to keep IME processes around for faster keyboard switching.
371      */
372     public static final int BIND_TREAT_LIKE_ACTIVITY = 0x08000000;
373 
374     /**
375      * @hide An idea that is not yet implemented.
376      * Flag for {@link #bindService}: If binding from an activity, consider
377      * this service to be visible like the binding activity is.  That is,
378      * it will be treated as something more important to keep around than
379      * invisible background activities.  This will impact the number of
380      * recent activities the user can switch between without having them
381      * restart.  There is no guarantee this will be respected, as the system
382      * tries to balance such requests from one app vs. the importantance of
383      * keeping other apps around.
384      */
385     public static final int BIND_VISIBLE = 0x10000000;
386 
387     /**
388      * @hide
389      * Flag for {@link #bindService}: Consider this binding to be causing the target
390      * process to be showing UI, so it will be do a UI_HIDDEN memory trim when it goes
391      * away.
392      */
393     public static final int BIND_SHOWING_UI = 0x20000000;
394 
395     /**
396      * Flag for {@link #bindService}: Don't consider the bound service to be
397      * visible, even if the caller is visible.
398      * @hide
399      */
400     public static final int BIND_NOT_VISIBLE = 0x40000000;
401 
402     /**
403      * Flag for {@link #bindService}: The service being bound is an
404      * {@link android.R.attr#isolatedProcess isolated},
405      * {@link android.R.attr#externalService external} service.  This binds the service into the
406      * calling application's package, rather than the package in which the service is declared.
407      * <p>
408      * When using this flag, the code for the service being bound will execute under the calling
409      * application's package name and user ID.  Because the service must be an isolated process,
410      * it will not have direct access to the application's data, though.
411      *
412      * The purpose of this flag is to allow applications to provide services that are attributed
413      * to the app using the service, rather than the application providing the service.
414      * </p>
415      */
416     public static final int BIND_EXTERNAL_SERVICE = 0x80000000;
417 
418     /** @hide */
419     @IntDef(flag = true, prefix = { "RECEIVER_VISIBLE_" }, value = {
420             RECEIVER_VISIBLE_TO_INSTANT_APPS
421     })
422     @Retention(RetentionPolicy.SOURCE)
423     public @interface RegisterReceiverFlags {}
424 
425     /**
426      * Flag for {@link #registerReceiver}: The receiver can receive broadcasts from Instant Apps.
427      */
428     public static final int RECEIVER_VISIBLE_TO_INSTANT_APPS = 0x1;
429 
430     /**
431      * Returns an AssetManager instance for the application's package.
432      * <p>
433      * <strong>Note:</strong> Implementations of this method should return
434      * an AssetManager instance that is consistent with the Resources instance
435      * returned by {@link #getResources()}. For example, they should share the
436      * same {@link Configuration} object.
437      *
438      * @return an AssetManager instance for the application's package
439      * @see #getResources()
440      */
getAssets()441     public abstract AssetManager getAssets();
442 
443     /**
444      * Returns a Resources instance for the application's package.
445      * <p>
446      * <strong>Note:</strong> Implementations of this method should return
447      * a Resources instance that is consistent with the AssetManager instance
448      * returned by {@link #getAssets()}. For example, they should share the
449      * same {@link Configuration} object.
450      *
451      * @return a Resources instance for the application's package
452      * @see #getAssets()
453      */
getResources()454     public abstract Resources getResources();
455 
456     /** Return PackageManager instance to find global package information. */
getPackageManager()457     public abstract PackageManager getPackageManager();
458 
459     /** Return a ContentResolver instance for your application's package. */
getContentResolver()460     public abstract ContentResolver getContentResolver();
461 
462     /**
463      * Return the Looper for the main thread of the current process.  This is
464      * the thread used to dispatch calls to application components (activities,
465      * services, etc).
466      * <p>
467      * By definition, this method returns the same result as would be obtained
468      * by calling {@link Looper#getMainLooper() Looper.getMainLooper()}.
469      * </p>
470      *
471      * @return The main looper.
472      */
getMainLooper()473     public abstract Looper getMainLooper();
474 
475     /**
476      * Return an {@link Executor} that will run enqueued tasks on the main
477      * thread associated with this context. This is the thread used to dispatch
478      * calls to application components (activities, services, etc).
479      */
getMainExecutor()480     public Executor getMainExecutor() {
481         // This is pretty inefficient, which is why ContextImpl overrides it
482         return new HandlerExecutor(new Handler(getMainLooper()));
483     }
484 
485     /**
486      * Return the context of the single, global Application object of the
487      * current process.  This generally should only be used if you need a
488      * Context whose lifecycle is separate from the current context, that is
489      * tied to the lifetime of the process rather than the current component.
490      *
491      * <p>Consider for example how this interacts with
492      * {@link #registerReceiver(BroadcastReceiver, IntentFilter)}:
493      * <ul>
494      * <li> <p>If used from an Activity context, the receiver is being registered
495      * within that activity.  This means that you are expected to unregister
496      * before the activity is done being destroyed; in fact if you do not do
497      * so, the framework will clean up your leaked registration as it removes
498      * the activity and log an error.  Thus, if you use the Activity context
499      * to register a receiver that is static (global to the process, not
500      * associated with an Activity instance) then that registration will be
501      * removed on you at whatever point the activity you used is destroyed.
502      * <li> <p>If used from the Context returned here, the receiver is being
503      * registered with the global state associated with your application.  Thus
504      * it will never be unregistered for you.  This is necessary if the receiver
505      * is associated with static data, not a particular component.  However
506      * using the ApplicationContext elsewhere can easily lead to serious leaks
507      * if you forget to unregister, unbind, etc.
508      * </ul>
509      */
getApplicationContext()510     public abstract Context getApplicationContext();
511 
512     /** Non-activity related autofill ids are unique in the app */
513     private static int sLastAutofillId = View.NO_ID;
514 
515     /**
516      * Gets the next autofill ID.
517      *
518      * <p>All IDs will be smaller or the same as {@link View#LAST_APP_AUTOFILL_ID}. All IDs
519      * returned will be unique.
520      *
521      * @return A ID that is unique in the process
522      *
523      * {@hide}
524      */
getNextAutofillId()525     public int getNextAutofillId() {
526         if (sLastAutofillId == View.LAST_APP_AUTOFILL_ID - 1) {
527             sLastAutofillId = View.NO_ID;
528         }
529 
530         sLastAutofillId++;
531 
532         return sLastAutofillId;
533     }
534 
535     /**
536      * Add a new {@link ComponentCallbacks} to the base application of the
537      * Context, which will be called at the same times as the ComponentCallbacks
538      * methods of activities and other components are called.  Note that you
539      * <em>must</em> be sure to use {@link #unregisterComponentCallbacks} when
540      * appropriate in the future; this will not be removed for you.
541      *
542      * @param callback The interface to call.  This can be either a
543      * {@link ComponentCallbacks} or {@link ComponentCallbacks2} interface.
544      */
registerComponentCallbacks(ComponentCallbacks callback)545     public void registerComponentCallbacks(ComponentCallbacks callback) {
546         getApplicationContext().registerComponentCallbacks(callback);
547     }
548 
549     /**
550      * Remove a {@link ComponentCallbacks} object that was previously registered
551      * with {@link #registerComponentCallbacks(ComponentCallbacks)}.
552      */
unregisterComponentCallbacks(ComponentCallbacks callback)553     public void unregisterComponentCallbacks(ComponentCallbacks callback) {
554         getApplicationContext().unregisterComponentCallbacks(callback);
555     }
556 
557     /**
558      * Return a localized, styled CharSequence from the application's package's
559      * default string table.
560      *
561      * @param resId Resource id for the CharSequence text
562      */
563     @NonNull
getText(@tringRes int resId)564     public final CharSequence getText(@StringRes int resId) {
565         return getResources().getText(resId);
566     }
567 
568     /**
569      * Returns a localized string from the application's package's
570      * default string table.
571      *
572      * @param resId Resource id for the string
573      * @return The string data associated with the resource, stripped of styled
574      *         text information.
575      */
576     @NonNull
getString(@tringRes int resId)577     public final String getString(@StringRes int resId) {
578         return getResources().getString(resId);
579     }
580 
581     /**
582      * Returns a localized formatted string from the application's package's
583      * default string table, substituting the format arguments as defined in
584      * {@link java.util.Formatter} and {@link java.lang.String#format}.
585      *
586      * @param resId Resource id for the format string
587      * @param formatArgs The format arguments that will be used for
588      *                   substitution.
589      * @return The string data associated with the resource, formatted and
590      *         stripped of styled text information.
591      */
592     @NonNull
getString(@tringRes int resId, Object... formatArgs)593     public final String getString(@StringRes int resId, Object... formatArgs) {
594         return getResources().getString(resId, formatArgs);
595     }
596 
597     /**
598      * Returns a color associated with a particular resource ID and styled for
599      * the current theme.
600      *
601      * @param id The desired resource identifier, as generated by the aapt
602      *           tool. This integer encodes the package, type, and resource
603      *           entry. The value 0 is an invalid identifier.
604      * @return A single color value in the form 0xAARRGGBB.
605      * @throws android.content.res.Resources.NotFoundException if the given ID
606      *         does not exist.
607      */
608     @ColorInt
getColor(@olorRes int id)609     public final int getColor(@ColorRes int id) {
610         return getResources().getColor(id, getTheme());
611     }
612 
613     /**
614      * Returns a drawable object associated with a particular resource ID and
615      * styled for the current theme.
616      *
617      * @param id The desired resource identifier, as generated by the aapt
618      *           tool. This integer encodes the package, type, and resource
619      *           entry. The value 0 is an invalid identifier.
620      * @return An object that can be used to draw this resource.
621      * @throws android.content.res.Resources.NotFoundException if the given ID
622      *         does not exist.
623      */
624     @Nullable
getDrawable(@rawableRes int id)625     public final Drawable getDrawable(@DrawableRes int id) {
626         return getResources().getDrawable(id, getTheme());
627     }
628 
629     /**
630      * Returns a color state list associated with a particular resource ID and
631      * styled for the current theme.
632      *
633      * @param id The desired resource identifier, as generated by the aapt
634      *           tool. This integer encodes the package, type, and resource
635      *           entry. The value 0 is an invalid identifier.
636      * @return A color state list.
637      * @throws android.content.res.Resources.NotFoundException if the given ID
638      *         does not exist.
639      */
640     @NonNull
getColorStateList(@olorRes int id)641     public final ColorStateList getColorStateList(@ColorRes int id) {
642         return getResources().getColorStateList(id, getTheme());
643     }
644 
645      /**
646      * Set the base theme for this context.  Note that this should be called
647      * before any views are instantiated in the Context (for example before
648      * calling {@link android.app.Activity#setContentView} or
649      * {@link android.view.LayoutInflater#inflate}).
650      *
651      * @param resid The style resource describing the theme.
652      */
setTheme(@tyleRes int resid)653     public abstract void setTheme(@StyleRes int resid);
654 
655     /** @hide Needed for some internal implementation...  not public because
656      * you can't assume this actually means anything. */
getThemeResId()657     public int getThemeResId() {
658         return 0;
659     }
660 
661     /**
662      * Return the Theme object associated with this Context.
663      */
664     @ViewDebug.ExportedProperty(deepExport = true)
getTheme()665     public abstract Resources.Theme getTheme();
666 
667     /**
668      * Retrieve styled attribute information in this Context's theme.  See
669      * {@link android.content.res.Resources.Theme#obtainStyledAttributes(int[])}
670      * for more information.
671      *
672      * @see android.content.res.Resources.Theme#obtainStyledAttributes(int[])
673      */
obtainStyledAttributes(@tyleableRes int[] attrs)674     public final TypedArray obtainStyledAttributes(@StyleableRes int[] attrs) {
675         return getTheme().obtainStyledAttributes(attrs);
676     }
677 
678     /**
679      * Retrieve styled attribute information in this Context's theme.  See
680      * {@link android.content.res.Resources.Theme#obtainStyledAttributes(int, int[])}
681      * for more information.
682      *
683      * @see android.content.res.Resources.Theme#obtainStyledAttributes(int, int[])
684      */
obtainStyledAttributes( @tyleRes int resid, @StyleableRes int[] attrs)685     public final TypedArray obtainStyledAttributes(
686             @StyleRes int resid, @StyleableRes int[] attrs) throws Resources.NotFoundException {
687         return getTheme().obtainStyledAttributes(resid, attrs);
688     }
689 
690     /**
691      * Retrieve styled attribute information in this Context's theme.  See
692      * {@link android.content.res.Resources.Theme#obtainStyledAttributes(AttributeSet, int[], int, int)}
693      * for more information.
694      *
695      * @see android.content.res.Resources.Theme#obtainStyledAttributes(AttributeSet, int[], int, int)
696      */
obtainStyledAttributes( AttributeSet set, @StyleableRes int[] attrs)697     public final TypedArray obtainStyledAttributes(
698             AttributeSet set, @StyleableRes int[] attrs) {
699         return getTheme().obtainStyledAttributes(set, attrs, 0, 0);
700     }
701 
702     /**
703      * Retrieve styled attribute information in this Context's theme.  See
704      * {@link android.content.res.Resources.Theme#obtainStyledAttributes(AttributeSet, int[], int, int)}
705      * for more information.
706      *
707      * @see android.content.res.Resources.Theme#obtainStyledAttributes(AttributeSet, int[], int, int)
708      */
obtainStyledAttributes( AttributeSet set, @StyleableRes int[] attrs, @AttrRes int defStyleAttr, @StyleRes int defStyleRes)709     public final TypedArray obtainStyledAttributes(
710             AttributeSet set, @StyleableRes int[] attrs, @AttrRes int defStyleAttr,
711             @StyleRes int defStyleRes) {
712         return getTheme().obtainStyledAttributes(
713             set, attrs, defStyleAttr, defStyleRes);
714     }
715 
716     /**
717      * Return a class loader you can use to retrieve classes in this package.
718      */
getClassLoader()719     public abstract ClassLoader getClassLoader();
720 
721     /** Return the name of this application's package. */
getPackageName()722     public abstract String getPackageName();
723 
724     /** @hide Return the name of the base context this context is derived from. */
getBasePackageName()725     public abstract String getBasePackageName();
726 
727     /** @hide Return the package name that should be used for app ops calls from
728      * this context.  This is the same as {@link #getBasePackageName()} except in
729      * cases where system components are loaded into other app processes, in which
730      * case this will be the name of the primary package in that process (so that app
731      * ops uid verification will work with the name). */
getOpPackageName()732     public abstract String getOpPackageName();
733 
734     /** Return the full application info for this context's package. */
getApplicationInfo()735     public abstract ApplicationInfo getApplicationInfo();
736 
737     /**
738      * Return the full path to this context's primary Android package.
739      * The Android package is a ZIP file which contains the application's
740      * primary resources.
741      *
742      * <p>Note: this is not generally useful for applications, since they should
743      * not be directly accessing the file system.
744      *
745      * @return String Path to the resources.
746      */
getPackageResourcePath()747     public abstract String getPackageResourcePath();
748 
749     /**
750      * Return the full path to this context's primary Android package.
751      * The Android package is a ZIP file which contains application's
752      * primary code and assets.
753      *
754      * <p>Note: this is not generally useful for applications, since they should
755      * not be directly accessing the file system.
756      *
757      * @return String Path to the code and assets.
758      */
getPackageCodePath()759     public abstract String getPackageCodePath();
760 
761     /**
762      * @hide
763      * @deprecated use {@link #getSharedPreferencesPath(String)}
764      */
765     @Deprecated
getSharedPrefsFile(String name)766     public File getSharedPrefsFile(String name) {
767         return getSharedPreferencesPath(name);
768     }
769 
770     /**
771      * Retrieve and hold the contents of the preferences file 'name', returning
772      * a SharedPreferences through which you can retrieve and modify its
773      * values.  Only one instance of the SharedPreferences object is returned
774      * to any callers for the same name, meaning they will see each other's
775      * edits as soon as they are made.
776      *
777      * This method is thead-safe.
778      *
779      * @param name Desired preferences file. If a preferences file by this name
780      * does not exist, it will be created when you retrieve an
781      * editor (SharedPreferences.edit()) and then commit changes (Editor.commit()).
782      * @param mode Operating mode.
783      *
784      * @return The single {@link SharedPreferences} instance that can be used
785      *         to retrieve and modify the preference values.
786      *
787      * @see #MODE_PRIVATE
788      */
getSharedPreferences(String name, @PreferencesMode int mode)789     public abstract SharedPreferences getSharedPreferences(String name, @PreferencesMode int mode);
790 
791     /**
792      * Retrieve and hold the contents of the preferences file, returning
793      * a SharedPreferences through which you can retrieve and modify its
794      * values.  Only one instance of the SharedPreferences object is returned
795      * to any callers for the same name, meaning they will see each other's
796      * edits as soon as they are made.
797      *
798      * @param file Desired preferences file. If a preferences file by this name
799      * does not exist, it will be created when you retrieve an
800      * editor (SharedPreferences.edit()) and then commit changes (Editor.commit()).
801      * @param mode Operating mode.
802      *
803      * @return The single {@link SharedPreferences} instance that can be used
804      *         to retrieve and modify the preference values.
805      *
806      * @see #getSharedPreferencesPath(String)
807      * @see #MODE_PRIVATE
808      * @removed
809      */
getSharedPreferences(File file, @PreferencesMode int mode)810     public abstract SharedPreferences getSharedPreferences(File file, @PreferencesMode int mode);
811 
812     /**
813      * Move an existing shared preferences file from the given source storage
814      * context to this context. This is typically used to migrate data between
815      * storage locations after an upgrade, such as moving to device protected
816      * storage.
817      *
818      * @param sourceContext The source context which contains the existing
819      *            shared preferences to move.
820      * @param name The name of the shared preferences file.
821      * @return {@code true} if the move was successful or if the shared
822      *         preferences didn't exist in the source context, otherwise
823      *         {@code false}.
824      * @see #createDeviceProtectedStorageContext()
825      */
moveSharedPreferencesFrom(Context sourceContext, String name)826     public abstract boolean moveSharedPreferencesFrom(Context sourceContext, String name);
827 
828     /**
829      * Delete an existing shared preferences file.
830      *
831      * @param name The name (unique in the application package) of the shared
832      *            preferences file.
833      * @return {@code true} if the shared preferences file was successfully
834      *         deleted; else {@code false}.
835      * @see #getSharedPreferences(String, int)
836      */
deleteSharedPreferences(String name)837     public abstract boolean deleteSharedPreferences(String name);
838 
839     /** @hide */
reloadSharedPreferences()840     public abstract void reloadSharedPreferences();
841 
842     /**
843      * Open a private file associated with this Context's application package
844      * for reading.
845      *
846      * @param name The name of the file to open; can not contain path
847      *             separators.
848      *
849      * @return The resulting {@link FileInputStream}.
850      *
851      * @see #openFileOutput
852      * @see #fileList
853      * @see #deleteFile
854      * @see java.io.FileInputStream#FileInputStream(String)
855      */
openFileInput(String name)856     public abstract FileInputStream openFileInput(String name)
857         throws FileNotFoundException;
858 
859     /**
860      * Open a private file associated with this Context's application package
861      * for writing. Creates the file if it doesn't already exist.
862      * <p>
863      * No additional permissions are required for the calling app to read or
864      * write the returned file.
865      *
866      * @param name The name of the file to open; can not contain path
867      *            separators.
868      * @param mode Operating mode.
869      * @return The resulting {@link FileOutputStream}.
870      * @see #MODE_APPEND
871      * @see #MODE_PRIVATE
872      * @see #openFileInput
873      * @see #fileList
874      * @see #deleteFile
875      * @see java.io.FileOutputStream#FileOutputStream(String)
876      */
openFileOutput(String name, @FileMode int mode)877     public abstract FileOutputStream openFileOutput(String name, @FileMode int mode)
878         throws FileNotFoundException;
879 
880     /**
881      * Delete the given private file associated with this Context's
882      * application package.
883      *
884      * @param name The name of the file to delete; can not contain path
885      *             separators.
886      *
887      * @return {@code true} if the file was successfully deleted; else
888      *         {@code false}.
889      *
890      * @see #openFileInput
891      * @see #openFileOutput
892      * @see #fileList
893      * @see java.io.File#delete()
894      */
deleteFile(String name)895     public abstract boolean deleteFile(String name);
896 
897     /**
898      * Returns the absolute path on the filesystem where a file created with
899      * {@link #openFileOutput} is stored.
900      * <p>
901      * The returned path may change over time if the calling app is moved to an
902      * adopted storage device, so only relative paths should be persisted.
903      *
904      * @param name The name of the file for which you would like to get
905      *          its path.
906      *
907      * @return An absolute path to the given file.
908      *
909      * @see #openFileOutput
910      * @see #getFilesDir
911      * @see #getDir
912      */
getFileStreamPath(String name)913     public abstract File getFileStreamPath(String name);
914 
915     /**
916      * Returns the absolute path on the filesystem where a file created with
917      * {@link #getSharedPreferences(String, int)} is stored.
918      * <p>
919      * The returned path may change over time if the calling app is moved to an
920      * adopted storage device, so only relative paths should be persisted.
921      *
922      * @param name The name of the shared preferences for which you would like
923      *            to get a path.
924      * @return An absolute path to the given file.
925      * @see #getSharedPreferences(String, int)
926      * @removed
927      */
getSharedPreferencesPath(String name)928     public abstract File getSharedPreferencesPath(String name);
929 
930     /**
931      * Returns the absolute path to the directory on the filesystem where all
932      * private files belonging to this app are stored. Apps should not use this
933      * path directly; they should instead use {@link #getFilesDir()},
934      * {@link #getCacheDir()}, {@link #getDir(String, int)}, or other storage
935      * APIs on this class.
936      * <p>
937      * The returned path may change over time if the calling app is moved to an
938      * adopted storage device, so only relative paths should be persisted.
939      * <p>
940      * No additional permissions are required for the calling app to read or
941      * write files under the returned path.
942      *
943      * @see ApplicationInfo#dataDir
944      */
getDataDir()945     public abstract File getDataDir();
946 
947     /**
948      * Returns the absolute path to the directory on the filesystem where files
949      * created with {@link #openFileOutput} are stored.
950      * <p>
951      * The returned path may change over time if the calling app is moved to an
952      * adopted storage device, so only relative paths should be persisted.
953      * <p>
954      * No additional permissions are required for the calling app to read or
955      * write files under the returned path.
956      *
957      * @return The path of the directory holding application files.
958      * @see #openFileOutput
959      * @see #getFileStreamPath
960      * @see #getDir
961      */
getFilesDir()962     public abstract File getFilesDir();
963 
964     /**
965      * Returns the absolute path to the directory on the filesystem similar to
966      * {@link #getFilesDir()}. The difference is that files placed under this
967      * directory will be excluded from automatic backup to remote storage. See
968      * {@link android.app.backup.BackupAgent BackupAgent} for a full discussion
969      * of the automatic backup mechanism in Android.
970      * <p>
971      * The returned path may change over time if the calling app is moved to an
972      * adopted storage device, so only relative paths should be persisted.
973      * <p>
974      * No additional permissions are required for the calling app to read or
975      * write files under the returned path.
976      *
977      * @return The path of the directory holding application files that will not
978      *         be automatically backed up to remote storage.
979      * @see #openFileOutput
980      * @see #getFileStreamPath
981      * @see #getDir
982      * @see android.app.backup.BackupAgent
983      */
getNoBackupFilesDir()984     public abstract File getNoBackupFilesDir();
985 
986     /**
987      * Returns the absolute path to the directory on the primary shared/external
988      * storage device where the application can place persistent files it owns.
989      * These files are internal to the applications, and not typically visible
990      * to the user as media.
991      * <p>
992      * This is like {@link #getFilesDir()} in that these files will be deleted
993      * when the application is uninstalled, however there are some important
994      * differences:
995      * <ul>
996      * <li>Shared storage may not always be available, since removable media can
997      * be ejected by the user. Media state can be checked using
998      * {@link Environment#getExternalStorageState(File)}.
999      * <li>There is no security enforced with these files. For example, any
1000      * application holding
1001      * {@link android.Manifest.permission#WRITE_EXTERNAL_STORAGE} can write to
1002      * these files.
1003      * </ul>
1004      * <p>
1005      * If a shared storage device is emulated (as determined by
1006      * {@link Environment#isExternalStorageEmulated(File)}), it's contents are
1007      * backed by a private user data partition, which means there is little
1008      * benefit to storing data here instead of the private directories returned
1009      * by {@link #getFilesDir()}, etc.
1010      * <p>
1011      * Starting in {@link android.os.Build.VERSION_CODES#KITKAT}, no permissions
1012      * are required to read or write to the returned path; it's always
1013      * accessible to the calling app. This only applies to paths generated for
1014      * package name of the calling application. To access paths belonging to
1015      * other packages,
1016      * {@link android.Manifest.permission#WRITE_EXTERNAL_STORAGE} and/or
1017      * {@link android.Manifest.permission#READ_EXTERNAL_STORAGE} are required.
1018      * <p>
1019      * On devices with multiple users (as described by {@link UserManager}),
1020      * each user has their own isolated shared storage. Applications only have
1021      * access to the shared storage for the user they're running as.
1022      * <p>
1023      * The returned path may change over time if different shared storage media
1024      * is inserted, so only relative paths should be persisted.
1025      * <p>
1026      * Here is an example of typical code to manipulate a file in an
1027      * application's shared storage:
1028      * </p>
1029      * {@sample development/samples/ApiDemos/src/com/example/android/apis/content/ExternalStorage.java
1030      * private_file}
1031      * <p>
1032      * If you supply a non-null <var>type</var> to this function, the returned
1033      * file will be a path to a sub-directory of the given type. Though these
1034      * files are not automatically scanned by the media scanner, you can
1035      * explicitly add them to the media database with
1036      * {@link android.media.MediaScannerConnection#scanFile(Context, String[], String[], android.media.MediaScannerConnection.OnScanCompletedListener)
1037      * MediaScannerConnection.scanFile}. Note that this is not the same as
1038      * {@link android.os.Environment#getExternalStoragePublicDirectory
1039      * Environment.getExternalStoragePublicDirectory()}, which provides
1040      * directories of media shared by all applications. The directories returned
1041      * here are owned by the application, and their contents will be removed
1042      * when the application is uninstalled. Unlike
1043      * {@link android.os.Environment#getExternalStoragePublicDirectory
1044      * Environment.getExternalStoragePublicDirectory()}, the directory returned
1045      * here will be automatically created for you.
1046      * <p>
1047      * Here is an example of typical code to manipulate a picture in an
1048      * application's shared storage and add it to the media database:
1049      * </p>
1050      * {@sample development/samples/ApiDemos/src/com/example/android/apis/content/ExternalStorage.java
1051      * private_picture}
1052      *
1053      * @param type The type of files directory to return. May be {@code null}
1054      *            for the root of the files directory or one of the following
1055      *            constants for a subdirectory:
1056      *            {@link android.os.Environment#DIRECTORY_MUSIC},
1057      *            {@link android.os.Environment#DIRECTORY_PODCASTS},
1058      *            {@link android.os.Environment#DIRECTORY_RINGTONES},
1059      *            {@link android.os.Environment#DIRECTORY_ALARMS},
1060      *            {@link android.os.Environment#DIRECTORY_NOTIFICATIONS},
1061      *            {@link android.os.Environment#DIRECTORY_PICTURES}, or
1062      *            {@link android.os.Environment#DIRECTORY_MOVIES}.
1063      * @return the absolute path to application-specific directory. May return
1064      *         {@code null} if shared storage is not currently available.
1065      * @see #getFilesDir
1066      * @see #getExternalFilesDirs(String)
1067      * @see Environment#getExternalStorageState(File)
1068      * @see Environment#isExternalStorageEmulated(File)
1069      * @see Environment#isExternalStorageRemovable(File)
1070      */
1071     @Nullable
getExternalFilesDir(@ullable String type)1072     public abstract File getExternalFilesDir(@Nullable String type);
1073 
1074     /**
1075      * Returns absolute paths to application-specific directories on all
1076      * shared/external storage devices where the application can place
1077      * persistent files it owns. These files are internal to the application,
1078      * and not typically visible to the user as media.
1079      * <p>
1080      * This is like {@link #getFilesDir()} in that these files will be deleted
1081      * when the application is uninstalled, however there are some important
1082      * differences:
1083      * <ul>
1084      * <li>Shared storage may not always be available, since removable media can
1085      * be ejected by the user. Media state can be checked using
1086      * {@link Environment#getExternalStorageState(File)}.
1087      * <li>There is no security enforced with these files. For example, any
1088      * application holding
1089      * {@link android.Manifest.permission#WRITE_EXTERNAL_STORAGE} can write to
1090      * these files.
1091      * </ul>
1092      * <p>
1093      * If a shared storage device is emulated (as determined by
1094      * {@link Environment#isExternalStorageEmulated(File)}), it's contents are
1095      * backed by a private user data partition, which means there is little
1096      * benefit to storing data here instead of the private directories returned
1097      * by {@link #getFilesDir()}, etc.
1098      * <p>
1099      * Shared storage devices returned here are considered a stable part of the
1100      * device, including physical media slots under a protective cover. The
1101      * returned paths do not include transient devices, such as USB flash drives
1102      * connected to handheld devices.
1103      * <p>
1104      * An application may store data on any or all of the returned devices. For
1105      * example, an app may choose to store large files on the device with the
1106      * most available space, as measured by {@link StatFs}.
1107      * <p>
1108      * No additional permissions are required for the calling app to read or
1109      * write files under the returned path. Write access outside of these paths
1110      * on secondary external storage devices is not available.
1111      * <p>
1112      * The returned path may change over time if different shared storage media
1113      * is inserted, so only relative paths should be persisted.
1114      *
1115      * @param type The type of files directory to return. May be {@code null}
1116      *            for the root of the files directory or one of the following
1117      *            constants for a subdirectory:
1118      *            {@link android.os.Environment#DIRECTORY_MUSIC},
1119      *            {@link android.os.Environment#DIRECTORY_PODCASTS},
1120      *            {@link android.os.Environment#DIRECTORY_RINGTONES},
1121      *            {@link android.os.Environment#DIRECTORY_ALARMS},
1122      *            {@link android.os.Environment#DIRECTORY_NOTIFICATIONS},
1123      *            {@link android.os.Environment#DIRECTORY_PICTURES}, or
1124      *            {@link android.os.Environment#DIRECTORY_MOVIES}.
1125      * @return the absolute paths to application-specific directories. Some
1126      *         individual paths may be {@code null} if that shared storage is
1127      *         not currently available. The first path returned is the same as
1128      *         {@link #getExternalFilesDir(String)}.
1129      * @see #getExternalFilesDir(String)
1130      * @see Environment#getExternalStorageState(File)
1131      * @see Environment#isExternalStorageEmulated(File)
1132      * @see Environment#isExternalStorageRemovable(File)
1133      */
getExternalFilesDirs(String type)1134     public abstract File[] getExternalFilesDirs(String type);
1135 
1136     /**
1137      * Return the primary shared/external storage directory where this
1138      * application's OBB files (if there are any) can be found. Note if the
1139      * application does not have any OBB files, this directory may not exist.
1140      * <p>
1141      * This is like {@link #getFilesDir()} in that these files will be deleted
1142      * when the application is uninstalled, however there are some important
1143      * differences:
1144      * <ul>
1145      * <li>Shared storage may not always be available, since removable media can
1146      * be ejected by the user. Media state can be checked using
1147      * {@link Environment#getExternalStorageState(File)}.
1148      * <li>There is no security enforced with these files. For example, any
1149      * application holding
1150      * {@link android.Manifest.permission#WRITE_EXTERNAL_STORAGE} can write to
1151      * these files.
1152      * </ul>
1153      * <p>
1154      * Starting in {@link android.os.Build.VERSION_CODES#KITKAT}, no permissions
1155      * are required to read or write to the path that this method returns.
1156      * However, starting from {@link android.os.Build.VERSION_CODES#M},
1157      * to read the OBB expansion files, you must declare the
1158      * {@link android.Manifest.permission#READ_EXTERNAL_STORAGE} permission in the app manifest and ask for
1159      * permission at runtime as follows:
1160      * </p>
1161      * <p>
1162      * {@code <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"
1163      * android:maxSdkVersion="23" />}
1164      * </p>
1165      * <p>
1166      * Starting from {@link android.os.Build.VERSION_CODES#N},
1167      * {@link android.Manifest.permission#READ_EXTERNAL_STORAGE}
1168      * permission is not required, so don’t ask for this
1169      * permission at runtime. To handle both cases, your app must first try to read the OBB file,
1170      * and if it fails, you must request
1171      * {@link android.Manifest.permission#READ_EXTERNAL_STORAGE} permission at runtime.
1172      * </p>
1173      *
1174      * <p>
1175      * The following code snippet shows how to do this:
1176      * </p>
1177      *
1178      * <pre>
1179      * File obb = new File(obb_filename);
1180      * boolean open_failed = false;
1181      *
1182      * try {
1183      *     BufferedReader br = new BufferedReader(new FileReader(obb));
1184      *     open_failed = false;
1185      *     ReadObbFile(br);
1186      * } catch (IOException e) {
1187      *     open_failed = true;
1188      * }
1189      *
1190      * if (open_failed) {
1191      *     // request READ_EXTERNAL_STORAGE permission before reading OBB file
1192      *     ReadObbFileWithPermission();
1193      * }
1194      * </pre>
1195      *
1196      * On devices with multiple users (as described by {@link UserManager}),
1197      * multiple users may share the same OBB storage location. Applications
1198      * should ensure that multiple instances running under different users don't
1199      * interfere with each other.
1200      *
1201      * @return the absolute path to application-specific directory. May return
1202      *         {@code null} if shared storage is not currently available.
1203      * @see #getObbDirs()
1204      * @see Environment#getExternalStorageState(File)
1205      * @see Environment#isExternalStorageEmulated(File)
1206      * @see Environment#isExternalStorageRemovable(File)
1207      */
getObbDir()1208     public abstract File getObbDir();
1209 
1210     /**
1211      * Returns absolute paths to application-specific directories on all
1212      * shared/external storage devices where the application's OBB files (if
1213      * there are any) can be found. Note if the application does not have any
1214      * OBB files, these directories may not exist.
1215      * <p>
1216      * This is like {@link #getFilesDir()} in that these files will be deleted
1217      * when the application is uninstalled, however there are some important
1218      * differences:
1219      * <ul>
1220      * <li>Shared storage may not always be available, since removable media can
1221      * be ejected by the user. Media state can be checked using
1222      * {@link Environment#getExternalStorageState(File)}.
1223      * <li>There is no security enforced with these files. For example, any
1224      * application holding
1225      * {@link android.Manifest.permission#WRITE_EXTERNAL_STORAGE} can write to
1226      * these files.
1227      * </ul>
1228      * <p>
1229      * Shared storage devices returned here are considered a stable part of the
1230      * device, including physical media slots under a protective cover. The
1231      * returned paths do not include transient devices, such as USB flash drives
1232      * connected to handheld devices.
1233      * <p>
1234      * An application may store data on any or all of the returned devices. For
1235      * example, an app may choose to store large files on the device with the
1236      * most available space, as measured by {@link StatFs}.
1237      * <p>
1238      * No additional permissions are required for the calling app to read or
1239      * write files under the returned path. Write access outside of these paths
1240      * on secondary external storage devices is not available.
1241      *
1242      * @return the absolute paths to application-specific directories. Some
1243      *         individual paths may be {@code null} if that shared storage is
1244      *         not currently available. The first path returned is the same as
1245      *         {@link #getObbDir()}
1246      * @see #getObbDir()
1247      * @see Environment#getExternalStorageState(File)
1248      * @see Environment#isExternalStorageEmulated(File)
1249      * @see Environment#isExternalStorageRemovable(File)
1250      */
getObbDirs()1251     public abstract File[] getObbDirs();
1252 
1253     /**
1254      * Returns the absolute path to the application specific cache directory on
1255      * the filesystem.
1256      * <p>
1257      * The system will automatically delete files in this directory as disk
1258      * space is needed elsewhere on the device. The system will always delete
1259      * older files first, as reported by {@link File#lastModified()}. If
1260      * desired, you can exert more control over how files are deleted using
1261      * {@link StorageManager#setCacheBehaviorGroup(File, boolean)} and
1262      * {@link StorageManager#setCacheBehaviorTombstone(File, boolean)}.
1263      * <p>
1264      * Apps are strongly encouraged to keep their usage of cache space below the
1265      * quota returned by
1266      * {@link StorageManager#getCacheQuotaBytes(java.util.UUID)}. If your app
1267      * goes above this quota, your cached files will be some of the first to be
1268      * deleted when additional disk space is needed. Conversely, if your app
1269      * stays under this quota, your cached files will be some of the last to be
1270      * deleted when additional disk space is needed.
1271      * <p>
1272      * Note that your cache quota will change over time depending on how
1273      * frequently the user interacts with your app, and depending on how much
1274      * system-wide disk space is used.
1275      * <p>
1276      * The returned path may change over time if the calling app is moved to an
1277      * adopted storage device, so only relative paths should be persisted.
1278      * <p>
1279      * Apps require no extra permissions to read or write to the returned path,
1280      * since this path lives in their private storage.
1281      *
1282      * @return The path of the directory holding application cache files.
1283      * @see #openFileOutput
1284      * @see #getFileStreamPath
1285      * @see #getDir
1286      * @see #getExternalCacheDir
1287      */
getCacheDir()1288     public abstract File getCacheDir();
1289 
1290     /**
1291      * Returns the absolute path to the application specific cache directory on
1292      * the filesystem designed for storing cached code.
1293      * <p>
1294      * The system will delete any files stored in this location both when your
1295      * specific application is upgraded, and when the entire platform is
1296      * upgraded.
1297      * <p>
1298      * This location is optimal for storing compiled or optimized code generated
1299      * by your application at runtime.
1300      * <p>
1301      * The returned path may change over time if the calling app is moved to an
1302      * adopted storage device, so only relative paths should be persisted.
1303      * <p>
1304      * Apps require no extra permissions to read or write to the returned path,
1305      * since this path lives in their private storage.
1306      *
1307      * @return The path of the directory holding application code cache files.
1308      */
getCodeCacheDir()1309     public abstract File getCodeCacheDir();
1310 
1311     /**
1312      * Returns absolute path to application-specific directory on the primary
1313      * shared/external storage device where the application can place cache
1314      * files it owns. These files are internal to the application, and not
1315      * typically visible to the user as media.
1316      * <p>
1317      * This is like {@link #getCacheDir()} in that these files will be deleted
1318      * when the application is uninstalled, however there are some important
1319      * differences:
1320      * <ul>
1321      * <li>The platform does not always monitor the space available in shared
1322      * storage, and thus may not automatically delete these files. Apps should
1323      * always manage the maximum space used in this location. Currently the only
1324      * time files here will be deleted by the platform is when running on
1325      * {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR1} or later and
1326      * {@link Environment#isExternalStorageEmulated(File)} returns true.
1327      * <li>Shared storage may not always be available, since removable media can
1328      * be ejected by the user. Media state can be checked using
1329      * {@link Environment#getExternalStorageState(File)}.
1330      * <li>There is no security enforced with these files. For example, any
1331      * application holding
1332      * {@link android.Manifest.permission#WRITE_EXTERNAL_STORAGE} can write to
1333      * these files.
1334      * </ul>
1335      * <p>
1336      * If a shared storage device is emulated (as determined by
1337      * {@link Environment#isExternalStorageEmulated(File)}), its contents are
1338      * backed by a private user data partition, which means there is little
1339      * benefit to storing data here instead of the private directory returned by
1340      * {@link #getCacheDir()}.
1341      * <p>
1342      * Starting in {@link android.os.Build.VERSION_CODES#KITKAT}, no permissions
1343      * are required to read or write to the returned path; it's always
1344      * accessible to the calling app. This only applies to paths generated for
1345      * package name of the calling application. To access paths belonging to
1346      * other packages,
1347      * {@link android.Manifest.permission#WRITE_EXTERNAL_STORAGE} and/or
1348      * {@link android.Manifest.permission#READ_EXTERNAL_STORAGE} are required.
1349      * <p>
1350      * On devices with multiple users (as described by {@link UserManager}),
1351      * each user has their own isolated shared storage. Applications only have
1352      * access to the shared storage for the user they're running as.
1353      * <p>
1354      * The returned path may change over time if different shared storage media
1355      * is inserted, so only relative paths should be persisted.
1356      *
1357      * @return the absolute path to application-specific directory. May return
1358      *         {@code null} if shared storage is not currently available.
1359      * @see #getCacheDir
1360      * @see #getExternalCacheDirs()
1361      * @see Environment#getExternalStorageState(File)
1362      * @see Environment#isExternalStorageEmulated(File)
1363      * @see Environment#isExternalStorageRemovable(File)
1364      */
1365     @Nullable
getExternalCacheDir()1366     public abstract File getExternalCacheDir();
1367 
1368     /**
1369      * Returns absolute path to application-specific directory in the preloaded cache.
1370      * <p>Files stored in the cache directory can be deleted when the device runs low on storage.
1371      * There is no guarantee when these files will be deleted.
1372      * @hide
1373      */
1374     @Nullable
1375     @SystemApi
getPreloadsFileCache()1376     public abstract File getPreloadsFileCache();
1377 
1378     /**
1379      * Returns absolute paths to application-specific directories on all
1380      * shared/external storage devices where the application can place cache
1381      * files it owns. These files are internal to the application, and not
1382      * typically visible to the user as media.
1383      * <p>
1384      * This is like {@link #getCacheDir()} in that these files will be deleted
1385      * when the application is uninstalled, however there are some important
1386      * differences:
1387      * <ul>
1388      * <li>The platform does not always monitor the space available in shared
1389      * storage, and thus may not automatically delete these files. Apps should
1390      * always manage the maximum space used in this location. Currently the only
1391      * time files here will be deleted by the platform is when running on
1392      * {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR1} or later and
1393      * {@link Environment#isExternalStorageEmulated(File)} returns true.
1394      * <li>Shared storage may not always be available, since removable media can
1395      * be ejected by the user. Media state can be checked using
1396      * {@link Environment#getExternalStorageState(File)}.
1397      * <li>There is no security enforced with these files. For example, any
1398      * application holding
1399      * {@link android.Manifest.permission#WRITE_EXTERNAL_STORAGE} can write to
1400      * these files.
1401      * </ul>
1402      * <p>
1403      * If a shared storage device is emulated (as determined by
1404      * {@link Environment#isExternalStorageEmulated(File)}), it's contents are
1405      * backed by a private user data partition, which means there is little
1406      * benefit to storing data here instead of the private directory returned by
1407      * {@link #getCacheDir()}.
1408      * <p>
1409      * Shared storage devices returned here are considered a stable part of the
1410      * device, including physical media slots under a protective cover. The
1411      * returned paths do not include transient devices, such as USB flash drives
1412      * connected to handheld devices.
1413      * <p>
1414      * An application may store data on any or all of the returned devices. For
1415      * example, an app may choose to store large files on the device with the
1416      * most available space, as measured by {@link StatFs}.
1417      * <p>
1418      * No additional permissions are required for the calling app to read or
1419      * write files under the returned path. Write access outside of these paths
1420      * on secondary external storage devices is not available.
1421      * <p>
1422      * The returned paths may change over time if different shared storage media
1423      * is inserted, so only relative paths should be persisted.
1424      *
1425      * @return the absolute paths to application-specific directories. Some
1426      *         individual paths may be {@code null} if that shared storage is
1427      *         not currently available. The first path returned is the same as
1428      *         {@link #getExternalCacheDir()}.
1429      * @see #getExternalCacheDir()
1430      * @see Environment#getExternalStorageState(File)
1431      * @see Environment#isExternalStorageEmulated(File)
1432      * @see Environment#isExternalStorageRemovable(File)
1433      */
getExternalCacheDirs()1434     public abstract File[] getExternalCacheDirs();
1435 
1436     /**
1437      * Returns absolute paths to application-specific directories on all
1438      * shared/external storage devices where the application can place media
1439      * files. These files are scanned and made available to other apps through
1440      * {@link MediaStore}.
1441      * <p>
1442      * This is like {@link #getExternalFilesDirs} in that these files will be
1443      * deleted when the application is uninstalled, however there are some
1444      * important differences:
1445      * <ul>
1446      * <li>Shared storage may not always be available, since removable media can
1447      * be ejected by the user. Media state can be checked using
1448      * {@link Environment#getExternalStorageState(File)}.
1449      * <li>There is no security enforced with these files. For example, any
1450      * application holding
1451      * {@link android.Manifest.permission#WRITE_EXTERNAL_STORAGE} can write to
1452      * these files.
1453      * </ul>
1454      * <p>
1455      * Shared storage devices returned here are considered a stable part of the
1456      * device, including physical media slots under a protective cover. The
1457      * returned paths do not include transient devices, such as USB flash drives
1458      * connected to handheld devices.
1459      * <p>
1460      * An application may store data on any or all of the returned devices. For
1461      * example, an app may choose to store large files on the device with the
1462      * most available space, as measured by {@link StatFs}.
1463      * <p>
1464      * No additional permissions are required for the calling app to read or
1465      * write files under the returned path. Write access outside of these paths
1466      * on secondary external storage devices is not available.
1467      * <p>
1468      * The returned paths may change over time if different shared storage media
1469      * is inserted, so only relative paths should be persisted.
1470      *
1471      * @return the absolute paths to application-specific directories. Some
1472      *         individual paths may be {@code null} if that shared storage is
1473      *         not currently available.
1474      * @see Environment#getExternalStorageState(File)
1475      * @see Environment#isExternalStorageEmulated(File)
1476      * @see Environment#isExternalStorageRemovable(File)
1477      */
getExternalMediaDirs()1478     public abstract File[] getExternalMediaDirs();
1479 
1480     /**
1481      * Returns an array of strings naming the private files associated with
1482      * this Context's application package.
1483      *
1484      * @return Array of strings naming the private files.
1485      *
1486      * @see #openFileInput
1487      * @see #openFileOutput
1488      * @see #deleteFile
1489      */
fileList()1490     public abstract String[] fileList();
1491 
1492     /**
1493      * Retrieve, creating if needed, a new directory in which the application
1494      * can place its own custom data files.  You can use the returned File
1495      * object to create and access files in this directory.  Note that files
1496      * created through a File object will only be accessible by your own
1497      * application; you can only set the mode of the entire directory, not
1498      * of individual files.
1499      * <p>
1500      * The returned path may change over time if the calling app is moved to an
1501      * adopted storage device, so only relative paths should be persisted.
1502      * <p>
1503      * Apps require no extra permissions to read or write to the returned path,
1504      * since this path lives in their private storage.
1505      *
1506      * @param name Name of the directory to retrieve.  This is a directory
1507      * that is created as part of your application data.
1508      * @param mode Operating mode.
1509      *
1510      * @return A {@link File} object for the requested directory.  The directory
1511      * will have been created if it does not already exist.
1512      *
1513      * @see #openFileOutput(String, int)
1514      */
getDir(String name, @FileMode int mode)1515     public abstract File getDir(String name, @FileMode int mode);
1516 
1517     /**
1518      * Open a new private SQLiteDatabase associated with this Context's
1519      * application package. Create the database file if it doesn't exist.
1520      *
1521      * @param name The name (unique in the application package) of the database.
1522      * @param mode Operating mode.
1523      * @param factory An optional factory class that is called to instantiate a
1524      *            cursor when query is called.
1525      * @return The contents of a newly created database with the given name.
1526      * @throws android.database.sqlite.SQLiteException if the database file
1527      *             could not be opened.
1528      * @see #MODE_PRIVATE
1529      * @see #MODE_ENABLE_WRITE_AHEAD_LOGGING
1530      * @see #MODE_NO_LOCALIZED_COLLATORS
1531      * @see #deleteDatabase
1532      */
openOrCreateDatabase(String name, @DatabaseMode int mode, CursorFactory factory)1533     public abstract SQLiteDatabase openOrCreateDatabase(String name,
1534             @DatabaseMode int mode, CursorFactory factory);
1535 
1536     /**
1537      * Open a new private SQLiteDatabase associated with this Context's
1538      * application package. Creates the database file if it doesn't exist.
1539      * <p>
1540      * Accepts input param: a concrete instance of {@link DatabaseErrorHandler}
1541      * to be used to handle corruption when sqlite reports database corruption.
1542      * </p>
1543      *
1544      * @param name The name (unique in the application package) of the database.
1545      * @param mode Operating mode.
1546      * @param factory An optional factory class that is called to instantiate a
1547      *            cursor when query is called.
1548      * @param errorHandler the {@link DatabaseErrorHandler} to be used when
1549      *            sqlite reports database corruption. if null,
1550      *            {@link android.database.DefaultDatabaseErrorHandler} is
1551      *            assumed.
1552      * @return The contents of a newly created database with the given name.
1553      * @throws android.database.sqlite.SQLiteException if the database file
1554      *             could not be opened.
1555      * @see #MODE_PRIVATE
1556      * @see #MODE_ENABLE_WRITE_AHEAD_LOGGING
1557      * @see #MODE_NO_LOCALIZED_COLLATORS
1558      * @see #deleteDatabase
1559      */
openOrCreateDatabase(String name, @DatabaseMode int mode, CursorFactory factory, @Nullable DatabaseErrorHandler errorHandler)1560     public abstract SQLiteDatabase openOrCreateDatabase(String name,
1561             @DatabaseMode int mode, CursorFactory factory,
1562             @Nullable DatabaseErrorHandler errorHandler);
1563 
1564     /**
1565      * Move an existing database file from the given source storage context to
1566      * this context. This is typically used to migrate data between storage
1567      * locations after an upgrade, such as migrating to device protected
1568      * storage.
1569      * <p>
1570      * The database must be closed before being moved.
1571      *
1572      * @param sourceContext The source context which contains the existing
1573      *            database to move.
1574      * @param name The name of the database file.
1575      * @return {@code true} if the move was successful or if the database didn't
1576      *         exist in the source context, otherwise {@code false}.
1577      * @see #createDeviceProtectedStorageContext()
1578      */
moveDatabaseFrom(Context sourceContext, String name)1579     public abstract boolean moveDatabaseFrom(Context sourceContext, String name);
1580 
1581     /**
1582      * Delete an existing private SQLiteDatabase associated with this Context's
1583      * application package.
1584      *
1585      * @param name The name (unique in the application package) of the
1586      *             database.
1587      *
1588      * @return {@code true} if the database was successfully deleted; else {@code false}.
1589      *
1590      * @see #openOrCreateDatabase
1591      */
deleteDatabase(String name)1592     public abstract boolean deleteDatabase(String name);
1593 
1594     /**
1595      * Returns the absolute path on the filesystem where a database created with
1596      * {@link #openOrCreateDatabase} is stored.
1597      * <p>
1598      * The returned path may change over time if the calling app is moved to an
1599      * adopted storage device, so only relative paths should be persisted.
1600      *
1601      * @param name The name of the database for which you would like to get
1602      *          its path.
1603      *
1604      * @return An absolute path to the given database.
1605      *
1606      * @see #openOrCreateDatabase
1607      */
getDatabasePath(String name)1608     public abstract File getDatabasePath(String name);
1609 
1610     /**
1611      * Returns an array of strings naming the private databases associated with
1612      * this Context's application package.
1613      *
1614      * @return Array of strings naming the private databases.
1615      *
1616      * @see #openOrCreateDatabase
1617      * @see #deleteDatabase
1618      */
databaseList()1619     public abstract String[] databaseList();
1620 
1621     /**
1622      * @deprecated Use {@link android.app.WallpaperManager#getDrawable
1623      * WallpaperManager.get()} instead.
1624      */
1625     @Deprecated
getWallpaper()1626     public abstract Drawable getWallpaper();
1627 
1628     /**
1629      * @deprecated Use {@link android.app.WallpaperManager#peekDrawable
1630      * WallpaperManager.peek()} instead.
1631      */
1632     @Deprecated
peekWallpaper()1633     public abstract Drawable peekWallpaper();
1634 
1635     /**
1636      * @deprecated Use {@link android.app.WallpaperManager#getDesiredMinimumWidth()
1637      * WallpaperManager.getDesiredMinimumWidth()} instead.
1638      */
1639     @Deprecated
getWallpaperDesiredMinimumWidth()1640     public abstract int getWallpaperDesiredMinimumWidth();
1641 
1642     /**
1643      * @deprecated Use {@link android.app.WallpaperManager#getDesiredMinimumHeight()
1644      * WallpaperManager.getDesiredMinimumHeight()} instead.
1645      */
1646     @Deprecated
getWallpaperDesiredMinimumHeight()1647     public abstract int getWallpaperDesiredMinimumHeight();
1648 
1649     /**
1650      * @deprecated Use {@link android.app.WallpaperManager#setBitmap(Bitmap)
1651      * WallpaperManager.set()} instead.
1652      * <p>This method requires the caller to hold the permission
1653      * {@link android.Manifest.permission#SET_WALLPAPER}.
1654      */
1655     @Deprecated
setWallpaper(Bitmap bitmap)1656     public abstract void setWallpaper(Bitmap bitmap) throws IOException;
1657 
1658     /**
1659      * @deprecated Use {@link android.app.WallpaperManager#setStream(InputStream)
1660      * WallpaperManager.set()} instead.
1661      * <p>This method requires the caller to hold the permission
1662      * {@link android.Manifest.permission#SET_WALLPAPER}.
1663      */
1664     @Deprecated
setWallpaper(InputStream data)1665     public abstract void setWallpaper(InputStream data) throws IOException;
1666 
1667     /**
1668      * @deprecated Use {@link android.app.WallpaperManager#clear
1669      * WallpaperManager.clear()} instead.
1670      * <p>This method requires the caller to hold the permission
1671      * {@link android.Manifest.permission#SET_WALLPAPER}.
1672      */
1673     @Deprecated
clearWallpaper()1674     public abstract void clearWallpaper() throws IOException;
1675 
1676     /**
1677      * Same as {@link #startActivity(Intent, Bundle)} with no options
1678      * specified.
1679      *
1680      * @param intent The description of the activity to start.
1681      *
1682      * @throws ActivityNotFoundException &nbsp;
1683      *`
1684      * @see #startActivity(Intent, Bundle)
1685      * @see PackageManager#resolveActivity
1686      */
startActivity(@equiresPermission Intent intent)1687     public abstract void startActivity(@RequiresPermission Intent intent);
1688 
1689     /**
1690      * Version of {@link #startActivity(Intent)} that allows you to specify the
1691      * user the activity will be started for.  This is not available to applications
1692      * that are not pre-installed on the system image.
1693      * @param intent The description of the activity to start.
1694      * @param user The UserHandle of the user to start this activity for.
1695      * @throws ActivityNotFoundException &nbsp;
1696      * @hide
1697      */
1698     @RequiresPermission(android.Manifest.permission.INTERACT_ACROSS_USERS_FULL)
startActivityAsUser(@equiresPermission Intent intent, UserHandle user)1699     public void startActivityAsUser(@RequiresPermission Intent intent, UserHandle user) {
1700         throw new RuntimeException("Not implemented. Must override in a subclass.");
1701     }
1702 
1703     /**
1704      * Launch a new activity.  You will not receive any information about when
1705      * the activity exits.
1706      *
1707      * <p>Note that if this method is being called from outside of an
1708      * {@link android.app.Activity} Context, then the Intent must include
1709      * the {@link Intent#FLAG_ACTIVITY_NEW_TASK} launch flag.  This is because,
1710      * without being started from an existing Activity, there is no existing
1711      * task in which to place the new activity and thus it needs to be placed
1712      * in its own separate task.
1713      *
1714      * <p>This method throws {@link ActivityNotFoundException}
1715      * if there was no Activity found to run the given Intent.
1716      *
1717      * @param intent The description of the activity to start.
1718      * @param options Additional options for how the Activity should be started.
1719      * May be null if there are no options.  See {@link android.app.ActivityOptions}
1720      * for how to build the Bundle supplied here; there are no supported definitions
1721      * for building it manually.
1722      *
1723      * @throws ActivityNotFoundException &nbsp;
1724      *
1725      * @see #startActivity(Intent)
1726      * @see PackageManager#resolveActivity
1727      */
startActivity(@equiresPermission Intent intent, @Nullable Bundle options)1728     public abstract void startActivity(@RequiresPermission Intent intent,
1729             @Nullable Bundle options);
1730 
1731     /**
1732      * Version of {@link #startActivity(Intent, Bundle)} that allows you to specify the
1733      * user the activity will be started for.  This is not available to applications
1734      * that are not pre-installed on the system image.
1735      * @param intent The description of the activity to start.
1736      * @param options Additional options for how the Activity should be started.
1737      * May be null if there are no options.  See {@link android.app.ActivityOptions}
1738      * for how to build the Bundle supplied here; there are no supported definitions
1739      * for building it manually.
1740      * @param userId The UserHandle of the user to start this activity for.
1741      * @throws ActivityNotFoundException &nbsp;
1742      * @hide
1743      */
1744     @RequiresPermission(android.Manifest.permission.INTERACT_ACROSS_USERS_FULL)
startActivityAsUser(@equiresPermission Intent intent, @Nullable Bundle options, UserHandle userId)1745     public void startActivityAsUser(@RequiresPermission Intent intent, @Nullable Bundle options,
1746             UserHandle userId) {
1747         throw new RuntimeException("Not implemented. Must override in a subclass.");
1748     }
1749 
1750     /**
1751      * Version of {@link #startActivity(Intent, Bundle)} that returns a result to the caller. This
1752      * is only supported for Views and Fragments.
1753      * @param who The identifier for the calling element that will receive the result.
1754      * @param intent The intent to start.
1755      * @param requestCode The code that will be returned with onActivityResult() identifying this
1756      *          request.
1757      * @param options Additional options for how the Activity should be started.
1758      *          May be null if there are no options.  See {@link android.app.ActivityOptions}
1759      *          for how to build the Bundle supplied here; there are no supported definitions
1760      *          for building it manually.
1761      * @hide
1762      */
startActivityForResult( @onNull String who, Intent intent, int requestCode, @Nullable Bundle options)1763     public void startActivityForResult(
1764             @NonNull String who, Intent intent, int requestCode, @Nullable Bundle options) {
1765         throw new RuntimeException("This method is only implemented for Activity-based Contexts. "
1766                 + "Check canStartActivityForResult() before calling.");
1767     }
1768 
1769     /**
1770      * Identifies whether this Context instance will be able to process calls to
1771      * {@link #startActivityForResult(String, Intent, int, Bundle)}.
1772      * @hide
1773      */
canStartActivityForResult()1774     public boolean canStartActivityForResult() {
1775         return false;
1776     }
1777 
1778     /**
1779      * Same as {@link #startActivities(Intent[], Bundle)} with no options
1780      * specified.
1781      *
1782      * @param intents An array of Intents to be started.
1783      *
1784      * @throws ActivityNotFoundException &nbsp;
1785      *
1786      * @see #startActivities(Intent[], Bundle)
1787      * @see PackageManager#resolveActivity
1788      */
startActivities(@equiresPermission Intent[] intents)1789     public abstract void startActivities(@RequiresPermission Intent[] intents);
1790 
1791     /**
1792      * Launch multiple new activities.  This is generally the same as calling
1793      * {@link #startActivity(Intent)} for the first Intent in the array,
1794      * that activity during its creation calling {@link #startActivity(Intent)}
1795      * for the second entry, etc.  Note that unlike that approach, generally
1796      * none of the activities except the last in the array will be created
1797      * at this point, but rather will be created when the user first visits
1798      * them (due to pressing back from the activity on top).
1799      *
1800      * <p>This method throws {@link ActivityNotFoundException}
1801      * if there was no Activity found for <em>any</em> given Intent.  In this
1802      * case the state of the activity stack is undefined (some Intents in the
1803      * list may be on it, some not), so you probably want to avoid such situations.
1804      *
1805      * @param intents An array of Intents to be started.
1806      * @param options Additional options for how the Activity should be started.
1807      * See {@link android.content.Context#startActivity(Intent, Bundle)}
1808      * Context.startActivity(Intent, Bundle)} for more details.
1809      *
1810      * @throws ActivityNotFoundException &nbsp;
1811      *
1812      * @see #startActivities(Intent[])
1813      * @see PackageManager#resolveActivity
1814      */
startActivities(@equiresPermission Intent[] intents, Bundle options)1815     public abstract void startActivities(@RequiresPermission Intent[] intents, Bundle options);
1816 
1817     /**
1818      * @hide
1819      * Launch multiple new activities.  This is generally the same as calling
1820      * {@link #startActivity(Intent)} for the first Intent in the array,
1821      * that activity during its creation calling {@link #startActivity(Intent)}
1822      * for the second entry, etc.  Note that unlike that approach, generally
1823      * none of the activities except the last in the array will be created
1824      * at this point, but rather will be created when the user first visits
1825      * them (due to pressing back from the activity on top).
1826      *
1827      * <p>This method throws {@link ActivityNotFoundException}
1828      * if there was no Activity found for <em>any</em> given Intent.  In this
1829      * case the state of the activity stack is undefined (some Intents in the
1830      * list may be on it, some not), so you probably want to avoid such situations.
1831      *
1832      * @param intents An array of Intents to be started.
1833      * @param options Additional options for how the Activity should be started.
1834      * @param userHandle The user for whom to launch the activities
1835      * See {@link android.content.Context#startActivity(Intent, Bundle)}
1836      * Context.startActivity(Intent, Bundle)} for more details.
1837      *
1838      * @return The corresponding flag {@link ActivityManager#START_CANCELED},
1839      *         {@link ActivityManager#START_SUCCESS} etc. indicating whether the launch was
1840      *         successful.
1841      *
1842      * @throws ActivityNotFoundException &nbsp;
1843      *
1844      * @see #startActivities(Intent[])
1845      * @see PackageManager#resolveActivity
1846      */
1847     @RequiresPermission(android.Manifest.permission.INTERACT_ACROSS_USERS_FULL)
startActivitiesAsUser(Intent[] intents, Bundle options, UserHandle userHandle)1848     public int startActivitiesAsUser(Intent[] intents, Bundle options, UserHandle userHandle) {
1849         throw new RuntimeException("Not implemented. Must override in a subclass.");
1850     }
1851 
1852     /**
1853      * Same as {@link #startIntentSender(IntentSender, Intent, int, int, int, Bundle)}
1854      * with no options specified.
1855      *
1856      * @param intent The IntentSender to launch.
1857      * @param fillInIntent If non-null, this will be provided as the
1858      * intent parameter to {@link IntentSender#sendIntent}.
1859      * @param flagsMask Intent flags in the original IntentSender that you
1860      * would like to change.
1861      * @param flagsValues Desired values for any bits set in
1862      * <var>flagsMask</var>
1863      * @param extraFlags Always set to 0.
1864      *
1865      * @see #startActivity(Intent)
1866      * @see #startIntentSender(IntentSender, Intent, int, int, int, Bundle)
1867      */
startIntentSender(IntentSender intent, @Nullable Intent fillInIntent, @Intent.MutableFlags int flagsMask, @Intent.MutableFlags int flagsValues, int extraFlags)1868     public abstract void startIntentSender(IntentSender intent, @Nullable Intent fillInIntent,
1869             @Intent.MutableFlags int flagsMask, @Intent.MutableFlags int flagsValues,
1870             int extraFlags) throws IntentSender.SendIntentException;
1871 
1872     /**
1873      * Like {@link #startActivity(Intent, Bundle)}, but taking a IntentSender
1874      * to start.  If the IntentSender is for an activity, that activity will be started
1875      * as if you had called the regular {@link #startActivity(Intent)}
1876      * here; otherwise, its associated action will be executed (such as
1877      * sending a broadcast) as if you had called
1878      * {@link IntentSender#sendIntent IntentSender.sendIntent} on it.
1879      *
1880      * @param intent The IntentSender to launch.
1881      * @param fillInIntent If non-null, this will be provided as the
1882      * intent parameter to {@link IntentSender#sendIntent}.
1883      * @param flagsMask Intent flags in the original IntentSender that you
1884      * would like to change.
1885      * @param flagsValues Desired values for any bits set in
1886      * <var>flagsMask</var>
1887      * @param extraFlags Always set to 0.
1888      * @param options Additional options for how the Activity should be started.
1889      * See {@link android.content.Context#startActivity(Intent, Bundle)}
1890      * Context.startActivity(Intent, Bundle)} for more details.  If options
1891      * have also been supplied by the IntentSender, options given here will
1892      * override any that conflict with those given by the IntentSender.
1893      *
1894      * @see #startActivity(Intent, Bundle)
1895      * @see #startIntentSender(IntentSender, Intent, int, int, int)
1896      */
startIntentSender(IntentSender intent, @Nullable Intent fillInIntent, @Intent.MutableFlags int flagsMask, @Intent.MutableFlags int flagsValues, int extraFlags, @Nullable Bundle options)1897     public abstract void startIntentSender(IntentSender intent, @Nullable Intent fillInIntent,
1898             @Intent.MutableFlags int flagsMask, @Intent.MutableFlags int flagsValues,
1899             int extraFlags, @Nullable Bundle options) throws IntentSender.SendIntentException;
1900 
1901     /**
1902      * Broadcast the given intent to all interested BroadcastReceivers.  This
1903      * call is asynchronous; it returns immediately, and you will continue
1904      * executing while the receivers are run.  No results are propagated from
1905      * receivers and receivers can not abort the broadcast. If you want
1906      * to allow receivers to propagate results or abort the broadcast, you must
1907      * send an ordered broadcast using
1908      * {@link #sendOrderedBroadcast(Intent, String)}.
1909      *
1910      * <p>See {@link BroadcastReceiver} for more information on Intent broadcasts.
1911      *
1912      * @param intent The Intent to broadcast; all receivers matching this
1913      *               Intent will receive the broadcast.
1914      *
1915      * @see android.content.BroadcastReceiver
1916      * @see #registerReceiver
1917      * @see #sendBroadcast(Intent, String)
1918      * @see #sendOrderedBroadcast(Intent, String)
1919      * @see #sendOrderedBroadcast(Intent, String, BroadcastReceiver, Handler, int, String, Bundle)
1920      */
sendBroadcast(@equiresPermission Intent intent)1921     public abstract void sendBroadcast(@RequiresPermission Intent intent);
1922 
1923     /**
1924      * Broadcast the given intent to all interested BroadcastReceivers, allowing
1925      * an optional required permission to be enforced.  This
1926      * call is asynchronous; it returns immediately, and you will continue
1927      * executing while the receivers are run.  No results are propagated from
1928      * receivers and receivers can not abort the broadcast. If you want
1929      * to allow receivers to propagate results or abort the broadcast, you must
1930      * send an ordered broadcast using
1931      * {@link #sendOrderedBroadcast(Intent, String)}.
1932      *
1933      * <p>See {@link BroadcastReceiver} for more information on Intent broadcasts.
1934      *
1935      * @param intent The Intent to broadcast; all receivers matching this
1936      *               Intent will receive the broadcast.
1937      * @param receiverPermission (optional) String naming a permission that
1938      *               a receiver must hold in order to receive your broadcast.
1939      *               If null, no permission is required.
1940      *
1941      * @see android.content.BroadcastReceiver
1942      * @see #registerReceiver
1943      * @see #sendBroadcast(Intent)
1944      * @see #sendOrderedBroadcast(Intent, String)
1945      * @see #sendOrderedBroadcast(Intent, String, BroadcastReceiver, Handler, int, String, Bundle)
1946      */
sendBroadcast(@equiresPermission Intent intent, @Nullable String receiverPermission)1947     public abstract void sendBroadcast(@RequiresPermission Intent intent,
1948             @Nullable String receiverPermission);
1949 
1950 
1951     /**
1952      * Broadcast the given intent to all interested BroadcastReceivers, allowing
1953      * an array of required permissions to be enforced.  This call is asynchronous; it returns
1954      * immediately, and you will continue executing while the receivers are run.  No results are
1955      * propagated from receivers and receivers can not abort the broadcast. If you want to allow
1956      * receivers to propagate results or abort the broadcast, you must send an ordered broadcast
1957      * using {@link #sendOrderedBroadcast(Intent, String)}.
1958      *
1959      * <p>See {@link BroadcastReceiver} for more information on Intent broadcasts.
1960      *
1961      * @param intent The Intent to broadcast; all receivers matching this
1962      *               Intent will receive the broadcast.
1963      * @param receiverPermissions Array of names of permissions that a receiver must hold
1964      *                            in order to receive your broadcast.
1965      *                            If null or empty, no permissions are required.
1966      *
1967      * @see android.content.BroadcastReceiver
1968      * @see #registerReceiver
1969      * @see #sendBroadcast(Intent)
1970      * @see #sendOrderedBroadcast(Intent, String)
1971      * @see #sendOrderedBroadcast(Intent, String, BroadcastReceiver, Handler, int, String, Bundle)
1972      * @hide
1973      */
sendBroadcastMultiplePermissions(Intent intent, String[] receiverPermissions)1974     public abstract void sendBroadcastMultiplePermissions(Intent intent,
1975             String[] receiverPermissions);
1976 
1977     /**
1978      * Broadcast the given intent to all interested BroadcastReceivers, allowing
1979      * an array of required permissions to be enforced.  This call is asynchronous; it returns
1980      * immediately, and you will continue executing while the receivers are run.  No results are
1981      * propagated from receivers and receivers can not abort the broadcast. If you want to allow
1982      * receivers to propagate results or abort the broadcast, you must send an ordered broadcast
1983      * using {@link #sendOrderedBroadcast(Intent, String)}.
1984      *
1985      * <p>See {@link BroadcastReceiver} for more information on Intent broadcasts.
1986      *
1987      * @param intent The Intent to broadcast; all receivers matching this
1988      *               Intent will receive the broadcast.
1989      * @param user The user to send the broadcast to.
1990      * @param receiverPermissions Array of names of permissions that a receiver must hold
1991      *                            in order to receive your broadcast.
1992      *                            If null or empty, no permissions are required.
1993      *
1994      * @see android.content.BroadcastReceiver
1995      * @see #registerReceiver
1996      * @see #sendBroadcast(Intent)
1997      * @see #sendOrderedBroadcast(Intent, String)
1998      * @see #sendOrderedBroadcast(Intent, String, BroadcastReceiver, Handler, int, String, Bundle)
1999      * @hide
2000      */
sendBroadcastAsUserMultiplePermissions(Intent intent, UserHandle user, String[] receiverPermissions)2001     public abstract void sendBroadcastAsUserMultiplePermissions(Intent intent, UserHandle user,
2002             String[] receiverPermissions);
2003 
2004     /**
2005      * Broadcast the given intent to all interested BroadcastReceivers, allowing
2006      * an optional required permission to be enforced.  This
2007      * call is asynchronous; it returns immediately, and you will continue
2008      * executing while the receivers are run.  No results are propagated from
2009      * receivers and receivers can not abort the broadcast. If you want
2010      * to allow receivers to propagate results or abort the broadcast, you must
2011      * send an ordered broadcast using
2012      * {@link #sendOrderedBroadcast(Intent, String)}.
2013      *
2014      * <p>See {@link BroadcastReceiver} for more information on Intent broadcasts.
2015      *
2016      * @param intent The Intent to broadcast; all receivers matching this
2017      *               Intent will receive the broadcast.
2018      * @param receiverPermission (optional) String naming a permission that
2019      *               a receiver must hold in order to receive your broadcast.
2020      *               If null, no permission is required.
2021      * @param options (optional) Additional sending options, generated from a
2022      * {@link android.app.BroadcastOptions}.
2023      *
2024      * @see android.content.BroadcastReceiver
2025      * @see #registerReceiver
2026      * @see #sendBroadcast(Intent)
2027      * @see #sendOrderedBroadcast(Intent, String)
2028      * @see #sendOrderedBroadcast(Intent, String, BroadcastReceiver, Handler, int, String, Bundle)
2029      * @hide
2030      */
2031     @SystemApi
sendBroadcast(Intent intent, @Nullable String receiverPermission, @Nullable Bundle options)2032     public abstract void sendBroadcast(Intent intent,
2033             @Nullable String receiverPermission,
2034             @Nullable Bundle options);
2035 
2036     /**
2037      * Like {@link #sendBroadcast(Intent, String)}, but also allows specification
2038      * of an associated app op as per {@link android.app.AppOpsManager}.
2039      * @hide
2040      */
sendBroadcast(Intent intent, String receiverPermission, int appOp)2041     public abstract void sendBroadcast(Intent intent,
2042             String receiverPermission, int appOp);
2043 
2044     /**
2045      * Broadcast the given intent to all interested BroadcastReceivers, delivering
2046      * them one at a time to allow more preferred receivers to consume the
2047      * broadcast before it is delivered to less preferred receivers.  This
2048      * call is asynchronous; it returns immediately, and you will continue
2049      * executing while the receivers are run.
2050      *
2051      * <p>See {@link BroadcastReceiver} for more information on Intent broadcasts.
2052      *
2053      * @param intent The Intent to broadcast; all receivers matching this
2054      *               Intent will receive the broadcast.
2055      * @param receiverPermission (optional) String naming a permissions that
2056      *               a receiver must hold in order to receive your broadcast.
2057      *               If null, no permission is required.
2058      *
2059      * @see android.content.BroadcastReceiver
2060      * @see #registerReceiver
2061      * @see #sendBroadcast(Intent)
2062      * @see #sendOrderedBroadcast(Intent, String, BroadcastReceiver, Handler, int, String, Bundle)
2063      */
sendOrderedBroadcast(@equiresPermission Intent intent, @Nullable String receiverPermission)2064     public abstract void sendOrderedBroadcast(@RequiresPermission Intent intent,
2065             @Nullable String receiverPermission);
2066 
2067     /**
2068      * Version of {@link #sendBroadcast(Intent)} that allows you to
2069      * receive data back from the broadcast.  This is accomplished by
2070      * supplying your own BroadcastReceiver when calling, which will be
2071      * treated as a final receiver at the end of the broadcast -- its
2072      * {@link BroadcastReceiver#onReceive} method will be called with
2073      * the result values collected from the other receivers.  The broadcast will
2074      * be serialized in the same way as calling
2075      * {@link #sendOrderedBroadcast(Intent, String)}.
2076      *
2077      * <p>Like {@link #sendBroadcast(Intent)}, this method is
2078      * asynchronous; it will return before
2079      * resultReceiver.onReceive() is called.
2080      *
2081      * <p>See {@link BroadcastReceiver} for more information on Intent broadcasts.
2082      *
2083      * @param intent The Intent to broadcast; all receivers matching this
2084      *               Intent will receive the broadcast.
2085      * @param receiverPermission String naming a permissions that
2086      *               a receiver must hold in order to receive your broadcast.
2087      *               If null, no permission is required.
2088      * @param resultReceiver Your own BroadcastReceiver to treat as the final
2089      *                       receiver of the broadcast.
2090      * @param scheduler A custom Handler with which to schedule the
2091      *                  resultReceiver callback; if null it will be
2092      *                  scheduled in the Context's main thread.
2093      * @param initialCode An initial value for the result code.  Often
2094      *                    Activity.RESULT_OK.
2095      * @param initialData An initial value for the result data.  Often
2096      *                    null.
2097      * @param initialExtras An initial value for the result extras.  Often
2098      *                      null.
2099      *
2100      * @see #sendBroadcast(Intent)
2101      * @see #sendBroadcast(Intent, String)
2102      * @see #sendOrderedBroadcast(Intent, String)
2103      * @see android.content.BroadcastReceiver
2104      * @see #registerReceiver
2105      * @see android.app.Activity#RESULT_OK
2106      */
sendOrderedBroadcast(@equiresPermission @onNull Intent intent, @Nullable String receiverPermission, @Nullable BroadcastReceiver resultReceiver, @Nullable Handler scheduler, int initialCode, @Nullable String initialData, @Nullable Bundle initialExtras)2107     public abstract void sendOrderedBroadcast(@RequiresPermission @NonNull Intent intent,
2108             @Nullable String receiverPermission, @Nullable BroadcastReceiver resultReceiver,
2109             @Nullable Handler scheduler, int initialCode, @Nullable String initialData,
2110             @Nullable Bundle initialExtras);
2111 
2112     /**
2113      * Version of {@link #sendBroadcast(Intent)} that allows you to
2114      * receive data back from the broadcast.  This is accomplished by
2115      * supplying your own BroadcastReceiver when calling, which will be
2116      * treated as a final receiver at the end of the broadcast -- its
2117      * {@link BroadcastReceiver#onReceive} method will be called with
2118      * the result values collected from the other receivers.  The broadcast will
2119      * be serialized in the same way as calling
2120      * {@link #sendOrderedBroadcast(Intent, String)}.
2121      *
2122      * <p>Like {@link #sendBroadcast(Intent)}, this method is
2123      * asynchronous; it will return before
2124      * resultReceiver.onReceive() is called.
2125      *
2126      * <p>See {@link BroadcastReceiver} for more information on Intent broadcasts.
2127      *
2128      *
2129      * @param intent The Intent to broadcast; all receivers matching this
2130      *               Intent will receive the broadcast.
2131      * @param receiverPermission String naming a permissions that
2132      *               a receiver must hold in order to receive your broadcast.
2133      *               If null, no permission is required.
2134      * @param options (optional) Additional sending options, generated from a
2135      * {@link android.app.BroadcastOptions}.
2136      * @param resultReceiver Your own BroadcastReceiver to treat as the final
2137      *                       receiver of the broadcast.
2138      * @param scheduler A custom Handler with which to schedule the
2139      *                  resultReceiver callback; if null it will be
2140      *                  scheduled in the Context's main thread.
2141      * @param initialCode An initial value for the result code.  Often
2142      *                    Activity.RESULT_OK.
2143      * @param initialData An initial value for the result data.  Often
2144      *                    null.
2145      * @param initialExtras An initial value for the result extras.  Often
2146      *                      null.
2147      * @see #sendBroadcast(Intent)
2148      * @see #sendBroadcast(Intent, String)
2149      * @see #sendOrderedBroadcast(Intent, String)
2150      * @see android.content.BroadcastReceiver
2151      * @see #registerReceiver
2152      * @see android.app.Activity#RESULT_OK
2153      * @hide
2154      */
2155     @SystemApi
sendOrderedBroadcast(@onNull Intent intent, @Nullable String receiverPermission, @Nullable Bundle options, @Nullable BroadcastReceiver resultReceiver, @Nullable Handler scheduler, int initialCode, @Nullable String initialData, @Nullable Bundle initialExtras)2156     public abstract void sendOrderedBroadcast(@NonNull Intent intent,
2157             @Nullable String receiverPermission, @Nullable Bundle options,
2158             @Nullable BroadcastReceiver resultReceiver, @Nullable Handler scheduler,
2159             int initialCode, @Nullable String initialData, @Nullable Bundle initialExtras);
2160 
2161     /**
2162      * Like {@link #sendOrderedBroadcast(Intent, String, BroadcastReceiver, android.os.Handler,
2163      * int, String, android.os.Bundle)}, but also allows specification
2164      * of an associated app op as per {@link android.app.AppOpsManager}.
2165      * @hide
2166      */
sendOrderedBroadcast(Intent intent, String receiverPermission, int appOp, BroadcastReceiver resultReceiver, Handler scheduler, int initialCode, String initialData, Bundle initialExtras)2167     public abstract void sendOrderedBroadcast(Intent intent,
2168             String receiverPermission, int appOp, BroadcastReceiver resultReceiver,
2169             Handler scheduler, int initialCode, String initialData,
2170             Bundle initialExtras);
2171 
2172     /**
2173      * Version of {@link #sendBroadcast(Intent)} that allows you to specify the
2174      * user the broadcast will be sent to.  This is not available to applications
2175      * that are not pre-installed on the system image.
2176      * @param intent The intent to broadcast
2177      * @param user UserHandle to send the intent to.
2178      * @see #sendBroadcast(Intent)
2179      */
2180     @RequiresPermission(android.Manifest.permission.INTERACT_ACROSS_USERS)
sendBroadcastAsUser(@equiresPermission Intent intent, UserHandle user)2181     public abstract void sendBroadcastAsUser(@RequiresPermission Intent intent,
2182             UserHandle user);
2183 
2184     /**
2185      * Version of {@link #sendBroadcast(Intent, String)} that allows you to specify the
2186      * user the broadcast will be sent to.  This is not available to applications
2187      * that are not pre-installed on the system image.
2188      *
2189      * @param intent The Intent to broadcast; all receivers matching this
2190      *               Intent will receive the broadcast.
2191      * @param user UserHandle to send the intent to.
2192      * @param receiverPermission (optional) String naming a permission that
2193      *               a receiver must hold in order to receive your broadcast.
2194      *               If null, no permission is required.
2195      *
2196      * @see #sendBroadcast(Intent, String)
2197      */
2198     @RequiresPermission(android.Manifest.permission.INTERACT_ACROSS_USERS)
sendBroadcastAsUser(@equiresPermission Intent intent, UserHandle user, @Nullable String receiverPermission)2199     public abstract void sendBroadcastAsUser(@RequiresPermission Intent intent,
2200             UserHandle user, @Nullable String receiverPermission);
2201 
2202     /**
2203      * Version of {@link #sendBroadcast(Intent, String, Bundle)} that allows you to specify the
2204      * user the broadcast will be sent to.  This is not available to applications
2205      * that are not pre-installed on the system image.
2206      *
2207      * @param intent The Intent to broadcast; all receivers matching this
2208      *               Intent will receive the broadcast.
2209      * @param user UserHandle to send the intent to.
2210      * @param receiverPermission (optional) String naming a permission that
2211      *               a receiver must hold in order to receive your broadcast.
2212      *               If null, no permission is required.
2213      * @param options (optional) Additional sending options, generated from a
2214      * {@link android.app.BroadcastOptions}.
2215      *
2216      * @see #sendBroadcast(Intent, String, Bundle)
2217      * @hide
2218      */
2219     @SystemApi
2220     @RequiresPermission(android.Manifest.permission.INTERACT_ACROSS_USERS)
sendBroadcastAsUser(@equiresPermission Intent intent, UserHandle user, @Nullable String receiverPermission, @Nullable Bundle options)2221     public abstract void sendBroadcastAsUser(@RequiresPermission Intent intent,
2222             UserHandle user, @Nullable String receiverPermission, @Nullable Bundle options);
2223 
2224     /**
2225      * Version of {@link #sendBroadcast(Intent, String)} that allows you to specify the
2226      * user the broadcast will be sent to.  This is not available to applications
2227      * that are not pre-installed on the system image.
2228      *
2229      * @param intent The Intent to broadcast; all receivers matching this
2230      *               Intent will receive the broadcast.
2231      * @param user UserHandle to send the intent to.
2232      * @param receiverPermission (optional) String naming a permission that
2233      *               a receiver must hold in order to receive your broadcast.
2234      *               If null, no permission is required.
2235      * @param appOp The app op associated with the broadcast.
2236      *
2237      * @see #sendBroadcast(Intent, String)
2238      *
2239      * @hide
2240      */
2241     @RequiresPermission(android.Manifest.permission.INTERACT_ACROSS_USERS)
sendBroadcastAsUser(@equiresPermission Intent intent, UserHandle user, @Nullable String receiverPermission, int appOp)2242     public abstract void sendBroadcastAsUser(@RequiresPermission Intent intent,
2243             UserHandle user, @Nullable String receiverPermission, int appOp);
2244 
2245     /**
2246      * Version of
2247      * {@link #sendOrderedBroadcast(Intent, String, BroadcastReceiver, Handler, int, String, Bundle)}
2248      * that allows you to specify the
2249      * user the broadcast will be sent to.  This is not available to applications
2250      * that are not pre-installed on the system image.
2251      *
2252      * <p>See {@link BroadcastReceiver} for more information on Intent broadcasts.
2253      *
2254      * @param intent The Intent to broadcast; all receivers matching this
2255      *               Intent will receive the broadcast.
2256      * @param user UserHandle to send the intent to.
2257      * @param receiverPermission String naming a permissions that
2258      *               a receiver must hold in order to receive your broadcast.
2259      *               If null, no permission is required.
2260      * @param resultReceiver Your own BroadcastReceiver to treat as the final
2261      *                       receiver of the broadcast.
2262      * @param scheduler A custom Handler with which to schedule the
2263      *                  resultReceiver callback; if null it will be
2264      *                  scheduled in the Context's main thread.
2265      * @param initialCode An initial value for the result code.  Often
2266      *                    Activity.RESULT_OK.
2267      * @param initialData An initial value for the result data.  Often
2268      *                    null.
2269      * @param initialExtras An initial value for the result extras.  Often
2270      *                      null.
2271      *
2272      * @see #sendOrderedBroadcast(Intent, String, BroadcastReceiver, Handler, int, String, Bundle)
2273      */
2274     @RequiresPermission(android.Manifest.permission.INTERACT_ACROSS_USERS)
sendOrderedBroadcastAsUser(@equiresPermission Intent intent, UserHandle user, @Nullable String receiverPermission, BroadcastReceiver resultReceiver, @Nullable Handler scheduler, int initialCode, @Nullable String initialData, @Nullable Bundle initialExtras)2275     public abstract void sendOrderedBroadcastAsUser(@RequiresPermission Intent intent,
2276             UserHandle user, @Nullable String receiverPermission, BroadcastReceiver resultReceiver,
2277             @Nullable Handler scheduler, int initialCode, @Nullable String initialData,
2278             @Nullable  Bundle initialExtras);
2279 
2280     /**
2281      * Similar to above but takes an appOp as well, to enforce restrictions.
2282      * @see #sendOrderedBroadcastAsUser(Intent, UserHandle, String,
2283      *       BroadcastReceiver, Handler, int, String, Bundle)
2284      * @hide
2285      */
2286     @RequiresPermission(android.Manifest.permission.INTERACT_ACROSS_USERS)
sendOrderedBroadcastAsUser(Intent intent, UserHandle user, @Nullable String receiverPermission, int appOp, BroadcastReceiver resultReceiver, @Nullable Handler scheduler, int initialCode, @Nullable String initialData, @Nullable Bundle initialExtras)2287     public abstract void sendOrderedBroadcastAsUser(Intent intent, UserHandle user,
2288             @Nullable String receiverPermission, int appOp, BroadcastReceiver resultReceiver,
2289             @Nullable Handler scheduler, int initialCode, @Nullable String initialData,
2290             @Nullable  Bundle initialExtras);
2291 
2292     /**
2293      * Similar to above but takes an appOp as well, to enforce restrictions, and an options Bundle.
2294      * @see #sendOrderedBroadcastAsUser(Intent, UserHandle, String,
2295      *       BroadcastReceiver, Handler, int, String, Bundle)
2296      * @hide
2297      */
2298     @RequiresPermission(android.Manifest.permission.INTERACT_ACROSS_USERS)
sendOrderedBroadcastAsUser(Intent intent, UserHandle user, @Nullable String receiverPermission, int appOp, @Nullable Bundle options, BroadcastReceiver resultReceiver, @Nullable Handler scheduler, int initialCode, @Nullable String initialData, @Nullable Bundle initialExtras)2299     public abstract void sendOrderedBroadcastAsUser(Intent intent, UserHandle user,
2300             @Nullable String receiverPermission, int appOp, @Nullable Bundle options,
2301             BroadcastReceiver resultReceiver, @Nullable Handler scheduler, int initialCode,
2302             @Nullable String initialData, @Nullable  Bundle initialExtras);
2303 
2304     /**
2305      * <p>Perform a {@link #sendBroadcast(Intent)} that is "sticky," meaning the
2306      * Intent you are sending stays around after the broadcast is complete,
2307      * so that others can quickly retrieve that data through the return
2308      * value of {@link #registerReceiver(BroadcastReceiver, IntentFilter)}.  In
2309      * all other ways, this behaves the same as
2310      * {@link #sendBroadcast(Intent)}.
2311      *
2312      * @deprecated Sticky broadcasts should not be used.  They provide no security (anyone
2313      * can access them), no protection (anyone can modify them), and many other problems.
2314      * The recommended pattern is to use a non-sticky broadcast to report that <em>something</em>
2315      * has changed, with another mechanism for apps to retrieve the current value whenever
2316      * desired.
2317      *
2318      * @param intent The Intent to broadcast; all receivers matching this
2319      * Intent will receive the broadcast, and the Intent will be held to
2320      * be re-broadcast to future receivers.
2321      *
2322      * @see #sendBroadcast(Intent)
2323      * @see #sendStickyOrderedBroadcast(Intent, BroadcastReceiver, Handler, int, String, Bundle)
2324      */
2325     @Deprecated
2326     @RequiresPermission(android.Manifest.permission.BROADCAST_STICKY)
sendStickyBroadcast(@equiresPermission Intent intent)2327     public abstract void sendStickyBroadcast(@RequiresPermission Intent intent);
2328 
2329     /**
2330      * <p>Version of {@link #sendStickyBroadcast} that allows you to
2331      * receive data back from the broadcast.  This is accomplished by
2332      * supplying your own BroadcastReceiver when calling, which will be
2333      * treated as a final receiver at the end of the broadcast -- its
2334      * {@link BroadcastReceiver#onReceive} method will be called with
2335      * the result values collected from the other receivers.  The broadcast will
2336      * be serialized in the same way as calling
2337      * {@link #sendOrderedBroadcast(Intent, String)}.
2338      *
2339      * <p>Like {@link #sendBroadcast(Intent)}, this method is
2340      * asynchronous; it will return before
2341      * resultReceiver.onReceive() is called.  Note that the sticky data
2342      * stored is only the data you initially supply to the broadcast, not
2343      * the result of any changes made by the receivers.
2344      *
2345      * <p>See {@link BroadcastReceiver} for more information on Intent broadcasts.
2346      *
2347      * @deprecated Sticky broadcasts should not be used.  They provide no security (anyone
2348      * can access them), no protection (anyone can modify them), and many other problems.
2349      * The recommended pattern is to use a non-sticky broadcast to report that <em>something</em>
2350      * has changed, with another mechanism for apps to retrieve the current value whenever
2351      * desired.
2352      *
2353      * @param intent The Intent to broadcast; all receivers matching this
2354      *               Intent will receive the broadcast.
2355      * @param resultReceiver Your own BroadcastReceiver to treat as the final
2356      *                       receiver of the broadcast.
2357      * @param scheduler A custom Handler with which to schedule the
2358      *                  resultReceiver callback; if null it will be
2359      *                  scheduled in the Context's main thread.
2360      * @param initialCode An initial value for the result code.  Often
2361      *                    Activity.RESULT_OK.
2362      * @param initialData An initial value for the result data.  Often
2363      *                    null.
2364      * @param initialExtras An initial value for the result extras.  Often
2365      *                      null.
2366      *
2367      * @see #sendBroadcast(Intent)
2368      * @see #sendBroadcast(Intent, String)
2369      * @see #sendOrderedBroadcast(Intent, String)
2370      * @see #sendStickyBroadcast(Intent)
2371      * @see android.content.BroadcastReceiver
2372      * @see #registerReceiver
2373      * @see android.app.Activity#RESULT_OK
2374      */
2375     @Deprecated
2376     @RequiresPermission(android.Manifest.permission.BROADCAST_STICKY)
sendStickyOrderedBroadcast(@equiresPermission Intent intent, BroadcastReceiver resultReceiver, @Nullable Handler scheduler, int initialCode, @Nullable String initialData, @Nullable Bundle initialExtras)2377     public abstract void sendStickyOrderedBroadcast(@RequiresPermission Intent intent,
2378             BroadcastReceiver resultReceiver,
2379             @Nullable Handler scheduler, int initialCode, @Nullable String initialData,
2380             @Nullable Bundle initialExtras);
2381 
2382     /**
2383      * <p>Remove the data previously sent with {@link #sendStickyBroadcast},
2384      * so that it is as if the sticky broadcast had never happened.
2385      *
2386      * @deprecated Sticky broadcasts should not be used.  They provide no security (anyone
2387      * can access them), no protection (anyone can modify them), and many other problems.
2388      * The recommended pattern is to use a non-sticky broadcast to report that <em>something</em>
2389      * has changed, with another mechanism for apps to retrieve the current value whenever
2390      * desired.
2391      *
2392      * @param intent The Intent that was previously broadcast.
2393      *
2394      * @see #sendStickyBroadcast
2395      */
2396     @Deprecated
2397     @RequiresPermission(android.Manifest.permission.BROADCAST_STICKY)
removeStickyBroadcast(@equiresPermission Intent intent)2398     public abstract void removeStickyBroadcast(@RequiresPermission Intent intent);
2399 
2400     /**
2401      * <p>Version of {@link #sendStickyBroadcast(Intent)} that allows you to specify the
2402      * user the broadcast will be sent to.  This is not available to applications
2403      * that are not pre-installed on the system image.
2404      *
2405      * @deprecated Sticky broadcasts should not be used.  They provide no security (anyone
2406      * can access them), no protection (anyone can modify them), and many other problems.
2407      * The recommended pattern is to use a non-sticky broadcast to report that <em>something</em>
2408      * has changed, with another mechanism for apps to retrieve the current value whenever
2409      * desired.
2410      *
2411      * @param intent The Intent to broadcast; all receivers matching this
2412      * Intent will receive the broadcast, and the Intent will be held to
2413      * be re-broadcast to future receivers.
2414      * @param user UserHandle to send the intent to.
2415      *
2416      * @see #sendBroadcast(Intent)
2417      */
2418     @Deprecated
2419     @RequiresPermission(allOf = {
2420             android.Manifest.permission.INTERACT_ACROSS_USERS,
2421             android.Manifest.permission.BROADCAST_STICKY
2422     })
sendStickyBroadcastAsUser(@equiresPermission Intent intent, UserHandle user)2423     public abstract void sendStickyBroadcastAsUser(@RequiresPermission Intent intent,
2424             UserHandle user);
2425 
2426     /**
2427      * @hide
2428      * This is just here for sending CONNECTIVITY_ACTION.
2429      */
2430     @Deprecated
2431     @RequiresPermission(allOf = {
2432             android.Manifest.permission.INTERACT_ACROSS_USERS,
2433             android.Manifest.permission.BROADCAST_STICKY
2434     })
sendStickyBroadcastAsUser(@equiresPermission Intent intent, UserHandle user, Bundle options)2435     public abstract void sendStickyBroadcastAsUser(@RequiresPermission Intent intent,
2436             UserHandle user, Bundle options);
2437 
2438     /**
2439      * <p>Version of
2440      * {@link #sendStickyOrderedBroadcast(Intent, BroadcastReceiver, Handler, int, String, Bundle)}
2441      * that allows you to specify the
2442      * user the broadcast will be sent to.  This is not available to applications
2443      * that are not pre-installed on the system image.
2444      *
2445      * <p>See {@link BroadcastReceiver} for more information on Intent broadcasts.
2446      *
2447      * @deprecated Sticky broadcasts should not be used.  They provide no security (anyone
2448      * can access them), no protection (anyone can modify them), and many other problems.
2449      * The recommended pattern is to use a non-sticky broadcast to report that <em>something</em>
2450      * has changed, with another mechanism for apps to retrieve the current value whenever
2451      * desired.
2452      *
2453      * @param intent The Intent to broadcast; all receivers matching this
2454      *               Intent will receive the broadcast.
2455      * @param user UserHandle to send the intent to.
2456      * @param resultReceiver Your own BroadcastReceiver to treat as the final
2457      *                       receiver of the broadcast.
2458      * @param scheduler A custom Handler with which to schedule the
2459      *                  resultReceiver callback; if null it will be
2460      *                  scheduled in the Context's main thread.
2461      * @param initialCode An initial value for the result code.  Often
2462      *                    Activity.RESULT_OK.
2463      * @param initialData An initial value for the result data.  Often
2464      *                    null.
2465      * @param initialExtras An initial value for the result extras.  Often
2466      *                      null.
2467      *
2468      * @see #sendStickyOrderedBroadcast(Intent, BroadcastReceiver, Handler, int, String, Bundle)
2469      */
2470     @Deprecated
2471     @RequiresPermission(allOf = {
2472             android.Manifest.permission.INTERACT_ACROSS_USERS,
2473             android.Manifest.permission.BROADCAST_STICKY
2474     })
sendStickyOrderedBroadcastAsUser(@equiresPermission Intent intent, UserHandle user, BroadcastReceiver resultReceiver, @Nullable Handler scheduler, int initialCode, @Nullable String initialData, @Nullable Bundle initialExtras)2475     public abstract void sendStickyOrderedBroadcastAsUser(@RequiresPermission Intent intent,
2476             UserHandle user, BroadcastReceiver resultReceiver,
2477             @Nullable Handler scheduler, int initialCode, @Nullable String initialData,
2478             @Nullable Bundle initialExtras);
2479 
2480     /**
2481      * <p>Version of {@link #removeStickyBroadcast(Intent)} that allows you to specify the
2482      * user the broadcast will be sent to.  This is not available to applications
2483      * that are not pre-installed on the system image.
2484      *
2485      * <p>You must hold the {@link android.Manifest.permission#BROADCAST_STICKY}
2486      * permission in order to use this API.  If you do not hold that
2487      * permission, {@link SecurityException} will be thrown.
2488      *
2489      * @deprecated Sticky broadcasts should not be used.  They provide no security (anyone
2490      * can access them), no protection (anyone can modify them), and many other problems.
2491      * The recommended pattern is to use a non-sticky broadcast to report that <em>something</em>
2492      * has changed, with another mechanism for apps to retrieve the current value whenever
2493      * desired.
2494      *
2495      * @param intent The Intent that was previously broadcast.
2496      * @param user UserHandle to remove the sticky broadcast from.
2497      *
2498      * @see #sendStickyBroadcastAsUser
2499      */
2500     @Deprecated
2501     @RequiresPermission(allOf = {
2502             android.Manifest.permission.INTERACT_ACROSS_USERS,
2503             android.Manifest.permission.BROADCAST_STICKY
2504     })
removeStickyBroadcastAsUser(@equiresPermission Intent intent, UserHandle user)2505     public abstract void removeStickyBroadcastAsUser(@RequiresPermission Intent intent,
2506             UserHandle user);
2507 
2508     /**
2509      * Register a BroadcastReceiver to be run in the main activity thread.  The
2510      * <var>receiver</var> will be called with any broadcast Intent that
2511      * matches <var>filter</var>, in the main application thread.
2512      *
2513      * <p>The system may broadcast Intents that are "sticky" -- these stay
2514      * around after the broadcast has finished, to be sent to any later
2515      * registrations. If your IntentFilter matches one of these sticky
2516      * Intents, that Intent will be returned by this function
2517      * <strong>and</strong> sent to your <var>receiver</var> as if it had just
2518      * been broadcast.
2519      *
2520      * <p>There may be multiple sticky Intents that match <var>filter</var>,
2521      * in which case each of these will be sent to <var>receiver</var>.  In
2522      * this case, only one of these can be returned directly by the function;
2523      * which of these that is returned is arbitrarily decided by the system.
2524      *
2525      * <p>If you know the Intent your are registering for is sticky, you can
2526      * supply null for your <var>receiver</var>.  In this case, no receiver is
2527      * registered -- the function simply returns the sticky Intent that
2528      * matches <var>filter</var>.  In the case of multiple matches, the same
2529      * rules as described above apply.
2530      *
2531      * <p>See {@link BroadcastReceiver} for more information on Intent broadcasts.
2532      *
2533      * <p>As of {@link android.os.Build.VERSION_CODES#ICE_CREAM_SANDWICH}, receivers
2534      * registered with this method will correctly respect the
2535      * {@link Intent#setPackage(String)} specified for an Intent being broadcast.
2536      * Prior to that, it would be ignored and delivered to all matching registered
2537      * receivers.  Be careful if using this for security.</p>
2538      *
2539      * <p class="note">Note: this method <em>cannot be called from a
2540      * {@link BroadcastReceiver} component;</em> that is, from a BroadcastReceiver
2541      * that is declared in an application's manifest.  It is okay, however, to call
2542      * this method from another BroadcastReceiver that has itself been registered
2543      * at run time with {@link #registerReceiver}, since the lifetime of such a
2544      * registered BroadcastReceiver is tied to the object that registered it.</p>
2545      *
2546      * @param receiver The BroadcastReceiver to handle the broadcast.
2547      * @param filter Selects the Intent broadcasts to be received.
2548      *
2549      * @return The first sticky intent found that matches <var>filter</var>,
2550      *         or null if there are none.
2551      *
2552      * @see #registerReceiver(BroadcastReceiver, IntentFilter, String, Handler)
2553      * @see #sendBroadcast
2554      * @see #unregisterReceiver
2555      */
2556     @Nullable
registerReceiver(@ullable BroadcastReceiver receiver, IntentFilter filter)2557     public abstract Intent registerReceiver(@Nullable BroadcastReceiver receiver,
2558                                             IntentFilter filter);
2559 
2560     /**
2561      * Register to receive intent broadcasts, with the receiver optionally being
2562      * exposed to Instant Apps. See
2563      * {@link #registerReceiver(BroadcastReceiver, IntentFilter)} for more
2564      * information. By default Instant Apps cannot interact with receivers in other
2565      * applications, this allows you to expose a receiver that Instant Apps can
2566      * interact with.
2567      *
2568      * <p>See {@link BroadcastReceiver} for more information on Intent broadcasts.
2569      *
2570      * <p>As of {@link android.os.Build.VERSION_CODES#ICE_CREAM_SANDWICH}, receivers
2571      * registered with this method will correctly respect the
2572      * {@link Intent#setPackage(String)} specified for an Intent being broadcast.
2573      * Prior to that, it would be ignored and delivered to all matching registered
2574      * receivers.  Be careful if using this for security.</p>
2575      *
2576      * @param receiver The BroadcastReceiver to handle the broadcast.
2577      * @param filter Selects the Intent broadcasts to be received.
2578      * @param flags Additional options for the receiver. May be 0 or
2579      *      {@link #RECEIVER_VISIBLE_TO_INSTANT_APPS}.
2580      *
2581      * @return The first sticky intent found that matches <var>filter</var>,
2582      *         or null if there are none.
2583      *
2584      * @see #registerReceiver(BroadcastReceiver, IntentFilter)
2585      * @see #sendBroadcast
2586      * @see #unregisterReceiver
2587      */
2588     @Nullable
registerReceiver(@ullable BroadcastReceiver receiver, IntentFilter filter, @RegisterReceiverFlags int flags)2589     public abstract Intent registerReceiver(@Nullable BroadcastReceiver receiver,
2590                                             IntentFilter filter,
2591                                             @RegisterReceiverFlags int flags);
2592 
2593     /**
2594      * Register to receive intent broadcasts, to run in the context of
2595      * <var>scheduler</var>.  See
2596      * {@link #registerReceiver(BroadcastReceiver, IntentFilter)} for more
2597      * information.  This allows you to enforce permissions on who can
2598      * broadcast intents to your receiver, or have the receiver run in
2599      * a different thread than the main application thread.
2600      *
2601      * <p>See {@link BroadcastReceiver} for more information on Intent broadcasts.
2602      *
2603      * <p>As of {@link android.os.Build.VERSION_CODES#ICE_CREAM_SANDWICH}, receivers
2604      * registered with this method will correctly respect the
2605      * {@link Intent#setPackage(String)} specified for an Intent being broadcast.
2606      * Prior to that, it would be ignored and delivered to all matching registered
2607      * receivers.  Be careful if using this for security.</p>
2608      *
2609      * @param receiver The BroadcastReceiver to handle the broadcast.
2610      * @param filter Selects the Intent broadcasts to be received.
2611      * @param broadcastPermission String naming a permissions that a
2612      *      broadcaster must hold in order to send an Intent to you.  If null,
2613      *      no permission is required.
2614      * @param scheduler Handler identifying the thread that will receive
2615      *      the Intent.  If null, the main thread of the process will be used.
2616      *
2617      * @return The first sticky intent found that matches <var>filter</var>,
2618      *         or null if there are none.
2619      *
2620      * @see #registerReceiver(BroadcastReceiver, IntentFilter)
2621      * @see #sendBroadcast
2622      * @see #unregisterReceiver
2623      */
2624     @Nullable
registerReceiver(BroadcastReceiver receiver, IntentFilter filter, @Nullable String broadcastPermission, @Nullable Handler scheduler)2625     public abstract Intent registerReceiver(BroadcastReceiver receiver,
2626             IntentFilter filter, @Nullable String broadcastPermission,
2627             @Nullable Handler scheduler);
2628 
2629     /**
2630      * Register to receive intent broadcasts, to run in the context of
2631      * <var>scheduler</var>. See
2632      * {@link #registerReceiver(BroadcastReceiver, IntentFilter, int)} and
2633      * {@link #registerReceiver(BroadcastReceiver, IntentFilter, String, Handler)}
2634      * for more information.
2635      *
2636      * <p>See {@link BroadcastReceiver} for more information on Intent broadcasts.
2637      *
2638      * <p>As of {@link android.os.Build.VERSION_CODES#ICE_CREAM_SANDWICH}, receivers
2639      * registered with this method will correctly respect the
2640      * {@link Intent#setPackage(String)} specified for an Intent being broadcast.
2641      * Prior to that, it would be ignored and delivered to all matching registered
2642      * receivers.  Be careful if using this for security.</p>
2643      *
2644      * @param receiver The BroadcastReceiver to handle the broadcast.
2645      * @param filter Selects the Intent broadcasts to be received.
2646      * @param broadcastPermission String naming a permissions that a
2647      *      broadcaster must hold in order to send an Intent to you.  If null,
2648      *      no permission is required.
2649      * @param scheduler Handler identifying the thread that will receive
2650      *      the Intent.  If null, the main thread of the process will be used.
2651      * @param flags Additional options for the receiver. May be 0 or
2652      *      {@link #RECEIVER_VISIBLE_TO_INSTANT_APPS}.
2653      *
2654      * @return The first sticky intent found that matches <var>filter</var>,
2655      *         or null if there are none.
2656      *
2657      * @see #registerReceiver(BroadcastReceiver, IntentFilter, int)
2658      * @see #registerReceiver(BroadcastReceiver, IntentFilter, String, Handler)
2659      * @see #sendBroadcast
2660      * @see #unregisterReceiver
2661      */
2662     @Nullable
registerReceiver(BroadcastReceiver receiver, IntentFilter filter, @Nullable String broadcastPermission, @Nullable Handler scheduler, @RegisterReceiverFlags int flags)2663     public abstract Intent registerReceiver(BroadcastReceiver receiver,
2664             IntentFilter filter, @Nullable String broadcastPermission,
2665             @Nullable Handler scheduler, @RegisterReceiverFlags int flags);
2666 
2667     /**
2668      * @hide
2669      * Same as {@link #registerReceiver(BroadcastReceiver, IntentFilter, String, Handler)
2670      * but for a specific user.  This receiver will receiver broadcasts that
2671      * are sent to the requested user.
2672      *
2673      * @param receiver The BroadcastReceiver to handle the broadcast.
2674      * @param user UserHandle to send the intent to.
2675      * @param filter Selects the Intent broadcasts to be received.
2676      * @param broadcastPermission String naming a permissions that a
2677      *      broadcaster must hold in order to send an Intent to you.  If null,
2678      *      no permission is required.
2679      * @param scheduler Handler identifying the thread that will receive
2680      *      the Intent.  If null, the main thread of the process will be used.
2681      *
2682      * @return The first sticky intent found that matches <var>filter</var>,
2683      *         or null if there are none.
2684      *
2685      * @see #registerReceiver(BroadcastReceiver, IntentFilter, String, Handler)
2686      * @see #sendBroadcast
2687      * @see #unregisterReceiver
2688      */
2689     @Nullable
2690     @RequiresPermission(android.Manifest.permission.INTERACT_ACROSS_USERS_FULL)
registerReceiverAsUser(BroadcastReceiver receiver, UserHandle user, IntentFilter filter, @Nullable String broadcastPermission, @Nullable Handler scheduler)2691     public abstract Intent registerReceiverAsUser(BroadcastReceiver receiver,
2692             UserHandle user, IntentFilter filter, @Nullable String broadcastPermission,
2693             @Nullable Handler scheduler);
2694 
2695     /**
2696      * Unregister a previously registered BroadcastReceiver.  <em>All</em>
2697      * filters that have been registered for this BroadcastReceiver will be
2698      * removed.
2699      *
2700      * @param receiver The BroadcastReceiver to unregister.
2701      *
2702      * @see #registerReceiver
2703      */
unregisterReceiver(BroadcastReceiver receiver)2704     public abstract void unregisterReceiver(BroadcastReceiver receiver);
2705 
2706     /**
2707      * Request that a given application service be started.  The Intent
2708      * should either contain the complete class name of a specific service
2709      * implementation to start, or a specific package name to target.  If the
2710      * Intent is less specified, it logs a warning about this.  In this case any of the
2711      * multiple matching services may be used.  If this service
2712      * is not already running, it will be instantiated and started (creating a
2713      * process for it if needed); if it is running then it remains running.
2714      *
2715      * <p>Every call to this method will result in a corresponding call to
2716      * the target service's {@link android.app.Service#onStartCommand} method,
2717      * with the <var>intent</var> given here.  This provides a convenient way
2718      * to submit jobs to a service without having to bind and call on to its
2719      * interface.
2720      *
2721      * <p>Using startService() overrides the default service lifetime that is
2722      * managed by {@link #bindService}: it requires the service to remain
2723      * running until {@link #stopService} is called, regardless of whether
2724      * any clients are connected to it.  Note that calls to startService()
2725      * do not nest: no matter how many times you call startService(),
2726      * a single call to {@link #stopService} will stop it.
2727      *
2728      * <p>The system attempts to keep running services around as much as
2729      * possible.  The only time they should be stopped is if the current
2730      * foreground application is using so many resources that the service needs
2731      * to be killed.  If any errors happen in the service's process, it will
2732      * automatically be restarted.
2733      *
2734      * <p>This function will throw {@link SecurityException} if you do not
2735      * have permission to start the given service.
2736      *
2737      * <p class="note"><strong>Note:</strong> Each call to startService()
2738      * results in significant work done by the system to manage service
2739      * lifecycle surrounding the processing of the intent, which can take
2740      * multiple milliseconds of CPU time. Due to this cost, startService()
2741      * should not be used for frequent intent delivery to a service, and only
2742      * for scheduling significant work. Use {@link #bindService bound services}
2743      * for high frequency calls.
2744      * </p>
2745      *
2746      * @param service Identifies the service to be started.  The Intent must be
2747      *      fully explicit (supplying a component name).  Additional values
2748      *      may be included in the Intent extras to supply arguments along with
2749      *      this specific start call.
2750      *
2751      * @return If the service is being started or is already running, the
2752      * {@link ComponentName} of the actual service that was started is
2753      * returned; else if the service does not exist null is returned.
2754      *
2755      * @throws SecurityException If the caller does not have permission to access the service
2756      * or the service can not be found.
2757      * @throws IllegalStateException If the application is in a state where the service
2758      * can not be started (such as not in the foreground in a state when services are allowed).
2759      *
2760      * @see #stopService
2761      * @see #bindService
2762      */
2763     @Nullable
startService(Intent service)2764     public abstract ComponentName startService(Intent service);
2765 
2766     /**
2767      * Similar to {@link #startService(Intent)}, but with an implicit promise that the
2768      * Service will call {@link android.app.Service#startForeground(int, android.app.Notification)
2769      * startForeground(int, android.app.Notification)} once it begins running.  The service is given
2770      * an amount of time comparable to the ANR interval to do this, otherwise the system
2771      * will automatically stop the service and declare the app ANR.
2772      *
2773      * <p>Unlike the ordinary {@link #startService(Intent)}, this method can be used
2774      * at any time, regardless of whether the app hosting the service is in a foreground
2775      * state.
2776      *
2777      * @param service Identifies the service to be started.  The Intent must be
2778      *      fully explicit (supplying a component name).  Additional values
2779      *      may be included in the Intent extras to supply arguments along with
2780      *      this specific start call.
2781      *
2782      * @return If the service is being started or is already running, the
2783      * {@link ComponentName} of the actual service that was started is
2784      * returned; else if the service does not exist null is returned.
2785      *
2786      * @throws SecurityException If the caller does not have permission to access the service
2787      * or the service can not be found.
2788      *
2789      * @see #stopService
2790      * @see android.app.Service#startForeground(int, android.app.Notification)
2791      */
2792     @Nullable
startForegroundService(Intent service)2793     public abstract ComponentName startForegroundService(Intent service);
2794 
2795     /**
2796      * @hide like {@link #startForegroundService(Intent)} but for a specific user.
2797      */
2798     @Nullable
2799     @RequiresPermission(android.Manifest.permission.INTERACT_ACROSS_USERS)
startForegroundServiceAsUser(Intent service, UserHandle user)2800     public abstract ComponentName startForegroundServiceAsUser(Intent service, UserHandle user);
2801 
2802     /**
2803      * Request that a given application service be stopped.  If the service is
2804      * not running, nothing happens.  Otherwise it is stopped.  Note that calls
2805      * to startService() are not counted -- this stops the service no matter
2806      * how many times it was started.
2807      *
2808      * <p>Note that if a stopped service still has {@link ServiceConnection}
2809      * objects bound to it with the {@link #BIND_AUTO_CREATE} set, it will
2810      * not be destroyed until all of these bindings are removed.  See
2811      * the {@link android.app.Service} documentation for more details on a
2812      * service's lifecycle.
2813      *
2814      * <p>This function will throw {@link SecurityException} if you do not
2815      * have permission to stop the given service.
2816      *
2817      * @param service Description of the service to be stopped.  The Intent must be either
2818      *      fully explicit (supplying a component name) or specify a specific package
2819      *      name it is targetted to.
2820      *
2821      * @return If there is a service matching the given Intent that is already
2822      * running, then it is stopped and {@code true} is returned; else {@code false} is returned.
2823      *
2824      * @throws SecurityException If the caller does not have permission to access the service
2825      * or the service can not be found.
2826      * @throws IllegalStateException If the application is in a state where the service
2827      * can not be started (such as not in the foreground in a state when services are allowed).
2828      *
2829      * @see #startService
2830      */
stopService(Intent service)2831     public abstract boolean stopService(Intent service);
2832 
2833     /**
2834      * @hide like {@link #startService(Intent)} but for a specific user.
2835      */
2836     @Nullable
2837     @RequiresPermission(android.Manifest.permission.INTERACT_ACROSS_USERS)
startServiceAsUser(Intent service, UserHandle user)2838     public abstract ComponentName startServiceAsUser(Intent service, UserHandle user);
2839 
2840     /**
2841      * @hide like {@link #stopService(Intent)} but for a specific user.
2842      */
2843     @RequiresPermission(android.Manifest.permission.INTERACT_ACROSS_USERS)
stopServiceAsUser(Intent service, UserHandle user)2844     public abstract boolean stopServiceAsUser(Intent service, UserHandle user);
2845 
2846     /**
2847      * Connect to an application service, creating it if needed.  This defines
2848      * a dependency between your application and the service.  The given
2849      * <var>conn</var> will receive the service object when it is created and be
2850      * told if it dies and restarts.  The service will be considered required
2851      * by the system only for as long as the calling context exists.  For
2852      * example, if this Context is an Activity that is stopped, the service will
2853      * not be required to continue running until the Activity is resumed.
2854      *
2855      * <p>If the service does not support binding, it may return {@code null} from
2856      * its {@link android.app.Service#onBind(Intent) onBind()} method.  If it does, then
2857      * the ServiceConnection's
2858      * {@link ServiceConnection#onNullBinding(ComponentName) onNullBinding()} method
2859      * will be invoked instead of
2860      * {@link ServiceConnection#onServiceConnected(ComponentName, IBinder) onServiceConnected()}.
2861      *
2862      * <p>This method will throw {@link SecurityException} if the calling app does not
2863      * have permission to bind to the given service.
2864      *
2865      * <p class="note">Note: this method <em>cannot be called from a
2866      * {@link BroadcastReceiver} component</em>.  A pattern you can use to
2867      * communicate from a BroadcastReceiver to a Service is to call
2868      * {@link #startService} with the arguments containing the command to be
2869      * sent, with the service calling its
2870      * {@link android.app.Service#stopSelf(int)} method when done executing
2871      * that command.  See the API demo App/Service/Service Start Arguments
2872      * Controller for an illustration of this.  It is okay, however, to use
2873      * this method from a BroadcastReceiver that has been registered with
2874      * {@link #registerReceiver}, since the lifetime of this BroadcastReceiver
2875      * is tied to another object (the one that registered it).</p>
2876      *
2877      * @param service Identifies the service to connect to.  The Intent must
2878      *      specify an explicit component name.
2879      * @param conn Receives information as the service is started and stopped.
2880      *      This must be a valid ServiceConnection object; it must not be null.
2881      * @param flags Operation options for the binding.  May be 0,
2882      *          {@link #BIND_AUTO_CREATE}, {@link #BIND_DEBUG_UNBIND},
2883      *          {@link #BIND_NOT_FOREGROUND}, {@link #BIND_ABOVE_CLIENT},
2884      *          {@link #BIND_ALLOW_OOM_MANAGEMENT}, or
2885      *          {@link #BIND_WAIVE_PRIORITY}.
2886      * @return {@code true} if the system is in the process of bringing up a
2887      *         service that your client has permission to bind to; {@code false}
2888      *         if the system couldn't find the service or if your client doesn't
2889      *         have permission to bind to it. If this value is {@code true}, you
2890      *         should later call {@link #unbindService} to release the
2891      *         connection.
2892      *
2893      * @throws SecurityException If the caller does not have permission to access the service
2894      * or the service can not be found.
2895      *
2896      * @see #unbindService
2897      * @see #startService
2898      * @see #BIND_AUTO_CREATE
2899      * @see #BIND_DEBUG_UNBIND
2900      * @see #BIND_NOT_FOREGROUND
2901      */
bindService(@equiresPermission Intent service, @NonNull ServiceConnection conn, @BindServiceFlags int flags)2902     public abstract boolean bindService(@RequiresPermission Intent service,
2903             @NonNull ServiceConnection conn, @BindServiceFlags int flags);
2904 
2905     /**
2906      * Same as {@link #bindService(Intent, ServiceConnection, int)}, but with an explicit userHandle
2907      * argument for use by system server and other multi-user aware code.
2908      * @hide
2909      */
2910     @SystemApi
2911     @SuppressWarnings("unused")
2912     @RequiresPermission(android.Manifest.permission.INTERACT_ACROSS_USERS)
bindServiceAsUser(@equiresPermission Intent service, ServiceConnection conn, int flags, UserHandle user)2913     public boolean bindServiceAsUser(@RequiresPermission Intent service, ServiceConnection conn,
2914             int flags, UserHandle user) {
2915         throw new RuntimeException("Not implemented. Must override in a subclass.");
2916     }
2917 
2918     /**
2919      * Same as {@link #bindService(Intent, ServiceConnection, int, UserHandle)}, but with an
2920      * explicit non-null Handler to run the ServiceConnection callbacks on.
2921      *
2922      * @hide
2923      */
2924     @RequiresPermission(android.Manifest.permission.INTERACT_ACROSS_USERS)
bindServiceAsUser(Intent service, ServiceConnection conn, int flags, Handler handler, UserHandle user)2925     public boolean bindServiceAsUser(Intent service, ServiceConnection conn, int flags,
2926             Handler handler, UserHandle user) {
2927         throw new RuntimeException("Not implemented. Must override in a subclass.");
2928     }
2929 
2930     /**
2931      * Disconnect from an application service.  You will no longer receive
2932      * calls as the service is restarted, and the service is now allowed to
2933      * stop at any time.
2934      *
2935      * @param conn The connection interface previously supplied to
2936      *             bindService().  This parameter must not be null.
2937      *
2938      * @see #bindService
2939      */
unbindService(@onNull ServiceConnection conn)2940     public abstract void unbindService(@NonNull ServiceConnection conn);
2941 
2942     /**
2943      * Start executing an {@link android.app.Instrumentation} class.  The given
2944      * Instrumentation component will be run by killing its target application
2945      * (if currently running), starting the target process, instantiating the
2946      * instrumentation component, and then letting it drive the application.
2947      *
2948      * <p>This function is not synchronous -- it returns as soon as the
2949      * instrumentation has started and while it is running.
2950      *
2951      * <p>Instrumentation is normally only allowed to run against a package
2952      * that is either unsigned or signed with a signature that the
2953      * the instrumentation package is also signed with (ensuring the target
2954      * trusts the instrumentation).
2955      *
2956      * @param className Name of the Instrumentation component to be run.
2957      * @param profileFile Optional path to write profiling data as the
2958      * instrumentation runs, or null for no profiling.
2959      * @param arguments Additional optional arguments to pass to the
2960      * instrumentation, or null.
2961      *
2962      * @return {@code true} if the instrumentation was successfully started,
2963      * else {@code false} if it could not be found.
2964      */
startInstrumentation(@onNull ComponentName className, @Nullable String profileFile, @Nullable Bundle arguments)2965     public abstract boolean startInstrumentation(@NonNull ComponentName className,
2966             @Nullable String profileFile, @Nullable Bundle arguments);
2967 
2968     /** @hide */
2969     @StringDef(suffix = { "_SERVICE" }, value = {
2970             POWER_SERVICE,
2971             WINDOW_SERVICE,
2972             LAYOUT_INFLATER_SERVICE,
2973             ACCOUNT_SERVICE,
2974             ACTIVITY_SERVICE,
2975             ALARM_SERVICE,
2976             NOTIFICATION_SERVICE,
2977             ACCESSIBILITY_SERVICE,
2978             CAPTIONING_SERVICE,
2979             KEYGUARD_SERVICE,
2980             LOCATION_SERVICE,
2981             //@hide: COUNTRY_DETECTOR,
2982             SEARCH_SERVICE,
2983             SENSOR_SERVICE,
2984             STORAGE_SERVICE,
2985             STORAGE_STATS_SERVICE,
2986             WALLPAPER_SERVICE,
2987             TIME_ZONE_RULES_MANAGER_SERVICE,
2988             VIBRATOR_SERVICE,
2989             //@hide: STATUS_BAR_SERVICE,
2990             CONNECTIVITY_SERVICE,
2991             IPSEC_SERVICE,
2992             //@hide: UPDATE_LOCK_SERVICE,
2993             //@hide: NETWORKMANAGEMENT_SERVICE,
2994             NETWORK_STATS_SERVICE,
2995             //@hide: NETWORK_POLICY_SERVICE,
2996             WIFI_SERVICE,
2997             WIFI_AWARE_SERVICE,
2998             WIFI_P2P_SERVICE,
2999             WIFI_SCANNING_SERVICE,
3000             //@hide: LOWPAN_SERVICE,
3001             //@hide: WIFI_RTT_SERVICE,
3002             //@hide: ETHERNET_SERVICE,
3003             WIFI_RTT_RANGING_SERVICE,
3004             NSD_SERVICE,
3005             AUDIO_SERVICE,
3006             FINGERPRINT_SERVICE,
3007             MEDIA_ROUTER_SERVICE,
3008             TELEPHONY_SERVICE,
3009             TELEPHONY_SUBSCRIPTION_SERVICE,
3010             CARRIER_CONFIG_SERVICE,
3011             TELECOM_SERVICE,
3012             CLIPBOARD_SERVICE,
3013             INPUT_METHOD_SERVICE,
3014             TEXT_SERVICES_MANAGER_SERVICE,
3015             TEXT_CLASSIFICATION_SERVICE,
3016             APPWIDGET_SERVICE,
3017             //@hide: VOICE_INTERACTION_MANAGER_SERVICE,
3018             //@hide: BACKUP_SERVICE,
3019             DROPBOX_SERVICE,
3020             //@hide: DEVICE_IDLE_CONTROLLER,
3021             DEVICE_POLICY_SERVICE,
3022             UI_MODE_SERVICE,
3023             DOWNLOAD_SERVICE,
3024             NFC_SERVICE,
3025             BLUETOOTH_SERVICE,
3026             //@hide: SIP_SERVICE,
3027             USB_SERVICE,
3028             LAUNCHER_APPS_SERVICE,
3029             //@hide: SERIAL_SERVICE,
3030             //@hide: HDMI_CONTROL_SERVICE,
3031             INPUT_SERVICE,
3032             DISPLAY_SERVICE,
3033             USER_SERVICE,
3034             RESTRICTIONS_SERVICE,
3035             APP_OPS_SERVICE,
3036             CAMERA_SERVICE,
3037             PRINT_SERVICE,
3038             CONSUMER_IR_SERVICE,
3039             //@hide: TRUST_SERVICE,
3040             TV_INPUT_SERVICE,
3041             //@hide: NETWORK_SCORE_SERVICE,
3042             USAGE_STATS_SERVICE,
3043             MEDIA_SESSION_SERVICE,
3044             BATTERY_SERVICE,
3045             JOB_SCHEDULER_SERVICE,
3046             //@hide: PERSISTENT_DATA_BLOCK_SERVICE,
3047             //@hide: OEM_LOCK_SERVICE,
3048             MEDIA_PROJECTION_SERVICE,
3049             MIDI_SERVICE,
3050             RADIO_SERVICE,
3051             HARDWARE_PROPERTIES_SERVICE,
3052             //@hide: SOUND_TRIGGER_SERVICE,
3053             SHORTCUT_SERVICE,
3054             //@hide: CONTEXTHUB_SERVICE,
3055             SYSTEM_HEALTH_SERVICE,
3056             //@hide: INCIDENT_SERVICE,
3057             //@hide: STATS_COMPANION_SERVICE,
3058             COMPANION_DEVICE_SERVICE,
3059             CROSS_PROFILE_APPS_SERVICE,
3060             //@hide: SYSTEM_UPDATE_SERVICE,
3061     })
3062     @Retention(RetentionPolicy.SOURCE)
3063     public @interface ServiceName {}
3064 
3065     /**
3066      * Return the handle to a system-level service by name. The class of the
3067      * returned object varies by the requested name. Currently available names
3068      * are:
3069      *
3070      * <dl>
3071      *  <dt> {@link #WINDOW_SERVICE} ("window")
3072      *  <dd> The top-level window manager in which you can place custom
3073      *  windows.  The returned object is a {@link android.view.WindowManager}.
3074      *  <dt> {@link #LAYOUT_INFLATER_SERVICE} ("layout_inflater")
3075      *  <dd> A {@link android.view.LayoutInflater} for inflating layout resources
3076      *  in this context.
3077      *  <dt> {@link #ACTIVITY_SERVICE} ("activity")
3078      *  <dd> A {@link android.app.ActivityManager} for interacting with the
3079      *  global activity state of the system.
3080      *  <dt> {@link #POWER_SERVICE} ("power")
3081      *  <dd> A {@link android.os.PowerManager} for controlling power
3082      *  management.
3083      *  <dt> {@link #ALARM_SERVICE} ("alarm")
3084      *  <dd> A {@link android.app.AlarmManager} for receiving intents at the
3085      *  time of your choosing.
3086      *  <dt> {@link #NOTIFICATION_SERVICE} ("notification")
3087      *  <dd> A {@link android.app.NotificationManager} for informing the user
3088      *   of background events.
3089      *  <dt> {@link #KEYGUARD_SERVICE} ("keyguard")
3090      *  <dd> A {@link android.app.KeyguardManager} for controlling keyguard.
3091      *  <dt> {@link #LOCATION_SERVICE} ("location")
3092      *  <dd> A {@link android.location.LocationManager} for controlling location
3093      *   (e.g., GPS) updates.
3094      *  <dt> {@link #SEARCH_SERVICE} ("search")
3095      *  <dd> A {@link android.app.SearchManager} for handling search.
3096      *  <dt> {@link #VIBRATOR_SERVICE} ("vibrator")
3097      *  <dd> A {@link android.os.Vibrator} for interacting with the vibrator
3098      *  hardware.
3099      *  <dt> {@link #CONNECTIVITY_SERVICE} ("connection")
3100      *  <dd> A {@link android.net.ConnectivityManager ConnectivityManager} for
3101      *  handling management of network connections.
3102      *  <dt> {@link #IPSEC_SERVICE} ("ipsec")
3103      *  <dd> A {@link android.net.IpSecManager IpSecManager} for managing IPSec on
3104      *  sockets and networks.
3105      *  <dt> {@link #WIFI_SERVICE} ("wifi")
3106      *  <dd> A {@link android.net.wifi.WifiManager WifiManager} for management of Wi-Fi
3107      *  connectivity.  On releases before NYC, it should only be obtained from an application
3108      *  context, and not from any other derived context to avoid memory leaks within the calling
3109      *  process.
3110      *  <dt> {@link #WIFI_AWARE_SERVICE} ("wifiaware")
3111      *  <dd> A {@link android.net.wifi.aware.WifiAwareManager WifiAwareManager} for management of
3112      * Wi-Fi Aware discovery and connectivity.
3113      *  <dt> {@link #WIFI_P2P_SERVICE} ("wifip2p")
3114      *  <dd> A {@link android.net.wifi.p2p.WifiP2pManager WifiP2pManager} for management of
3115      * Wi-Fi Direct connectivity.
3116      * <dt> {@link #INPUT_METHOD_SERVICE} ("input_method")
3117      * <dd> An {@link android.view.inputmethod.InputMethodManager InputMethodManager}
3118      * for management of input methods.
3119      * <dt> {@link #UI_MODE_SERVICE} ("uimode")
3120      * <dd> An {@link android.app.UiModeManager} for controlling UI modes.
3121      * <dt> {@link #DOWNLOAD_SERVICE} ("download")
3122      * <dd> A {@link android.app.DownloadManager} for requesting HTTP downloads
3123      * <dt> {@link #BATTERY_SERVICE} ("batterymanager")
3124      * <dd> A {@link android.os.BatteryManager} for managing battery state
3125      * <dt> {@link #JOB_SCHEDULER_SERVICE} ("taskmanager")
3126      * <dd>  A {@link android.app.job.JobScheduler} for managing scheduled tasks
3127      * <dt> {@link #NETWORK_STATS_SERVICE} ("netstats")
3128      * <dd> A {@link android.app.usage.NetworkStatsManager NetworkStatsManager} for querying network
3129      * usage statistics.
3130      * <dt> {@link #HARDWARE_PROPERTIES_SERVICE} ("hardware_properties")
3131      * <dd> A {@link android.os.HardwarePropertiesManager} for accessing hardware properties.
3132      * </dl>
3133      *
3134      * <p>Note:  System services obtained via this API may be closely associated with
3135      * the Context in which they are obtained from.  In general, do not share the
3136      * service objects between various different contexts (Activities, Applications,
3137      * Services, Providers, etc.)
3138      *
3139      * <p>Note: Instant apps, for which {@link PackageManager#isInstantApp()} returns true,
3140      * don't have access to the following system services: {@link #DEVICE_POLICY_SERVICE},
3141      * {@link #FINGERPRINT_SERVICE}, {@link #SHORTCUT_SERVICE}, {@link #USB_SERVICE},
3142      * {@link #WALLPAPER_SERVICE}, {@link #WIFI_P2P_SERVICE}, {@link #WIFI_SERVICE},
3143      * {@link #WIFI_AWARE_SERVICE}. For these services this method will return <code>null</code>.
3144      * Generally, if you are running as an instant app you should always check whether the result
3145      * of this method is null.
3146      *
3147      * @param name The name of the desired service.
3148      *
3149      * @return The service or null if the name does not exist.
3150      *
3151      * @see #WINDOW_SERVICE
3152      * @see android.view.WindowManager
3153      * @see #LAYOUT_INFLATER_SERVICE
3154      * @see android.view.LayoutInflater
3155      * @see #ACTIVITY_SERVICE
3156      * @see android.app.ActivityManager
3157      * @see #POWER_SERVICE
3158      * @see android.os.PowerManager
3159      * @see #ALARM_SERVICE
3160      * @see android.app.AlarmManager
3161      * @see #NOTIFICATION_SERVICE
3162      * @see android.app.NotificationManager
3163      * @see #KEYGUARD_SERVICE
3164      * @see android.app.KeyguardManager
3165      * @see #LOCATION_SERVICE
3166      * @see android.location.LocationManager
3167      * @see #SEARCH_SERVICE
3168      * @see android.app.SearchManager
3169      * @see #SENSOR_SERVICE
3170      * @see android.hardware.SensorManager
3171      * @see #STORAGE_SERVICE
3172      * @see android.os.storage.StorageManager
3173      * @see #VIBRATOR_SERVICE
3174      * @see android.os.Vibrator
3175      * @see #CONNECTIVITY_SERVICE
3176      * @see android.net.ConnectivityManager
3177      * @see #WIFI_SERVICE
3178      * @see android.net.wifi.WifiManager
3179      * @see #AUDIO_SERVICE
3180      * @see android.media.AudioManager
3181      * @see #MEDIA_ROUTER_SERVICE
3182      * @see android.media.MediaRouter
3183      * @see #TELEPHONY_SERVICE
3184      * @see android.telephony.TelephonyManager
3185      * @see #TELEPHONY_SUBSCRIPTION_SERVICE
3186      * @see android.telephony.SubscriptionManager
3187      * @see #CARRIER_CONFIG_SERVICE
3188      * @see android.telephony.CarrierConfigManager
3189      * @see #INPUT_METHOD_SERVICE
3190      * @see android.view.inputmethod.InputMethodManager
3191      * @see #UI_MODE_SERVICE
3192      * @see android.app.UiModeManager
3193      * @see #DOWNLOAD_SERVICE
3194      * @see android.app.DownloadManager
3195      * @see #BATTERY_SERVICE
3196      * @see android.os.BatteryManager
3197      * @see #JOB_SCHEDULER_SERVICE
3198      * @see android.app.job.JobScheduler
3199      * @see #NETWORK_STATS_SERVICE
3200      * @see android.app.usage.NetworkStatsManager
3201      * @see android.os.HardwarePropertiesManager
3202      * @see #HARDWARE_PROPERTIES_SERVICE
3203      */
getSystemService(@erviceName @onNull String name)3204     public abstract @Nullable Object getSystemService(@ServiceName @NonNull String name);
3205 
3206     /**
3207      * Return the handle to a system-level service by class.
3208      * <p>
3209      * Currently available classes are:
3210      * {@link android.view.WindowManager}, {@link android.view.LayoutInflater},
3211      * {@link android.app.ActivityManager}, {@link android.os.PowerManager},
3212      * {@link android.app.AlarmManager}, {@link android.app.NotificationManager},
3213      * {@link android.app.KeyguardManager}, {@link android.location.LocationManager},
3214      * {@link android.app.SearchManager}, {@link android.os.Vibrator},
3215      * {@link android.net.ConnectivityManager},
3216      * {@link android.net.wifi.WifiManager},
3217      * {@link android.media.AudioManager}, {@link android.media.MediaRouter},
3218      * {@link android.telephony.TelephonyManager}, {@link android.telephony.SubscriptionManager},
3219      * {@link android.view.inputmethod.InputMethodManager},
3220      * {@link android.app.UiModeManager}, {@link android.app.DownloadManager},
3221      * {@link android.os.BatteryManager}, {@link android.app.job.JobScheduler},
3222      * {@link android.app.usage.NetworkStatsManager}.
3223      * </p><p>
3224      * Note: System services obtained via this API may be closely associated with
3225      * the Context in which they are obtained from.  In general, do not share the
3226      * service objects between various different contexts (Activities, Applications,
3227      * Services, Providers, etc.)
3228      * </p>
3229      *
3230      * <p>Note: Instant apps, for which {@link PackageManager#isInstantApp()} returns true,
3231      * don't have access to the following system services: {@link #DEVICE_POLICY_SERVICE},
3232      * {@link #FINGERPRINT_SERVICE}, {@link #SHORTCUT_SERVICE}, {@link #USB_SERVICE},
3233      * {@link #WALLPAPER_SERVICE}, {@link #WIFI_P2P_SERVICE}, {@link #WIFI_SERVICE},
3234      * {@link #WIFI_AWARE_SERVICE}. For these services this method will return <code>null</code>.
3235      * Generally, if you are running as an instant app you should always check whether the result
3236      * of this method is null.
3237      *
3238      * @param serviceClass The class of the desired service.
3239      * @return The service or null if the class is not a supported system service.
3240      */
3241     @SuppressWarnings("unchecked")
getSystemService(@onNull Class<T> serviceClass)3242     public final @Nullable <T> T getSystemService(@NonNull Class<T> serviceClass) {
3243         // Because subclasses may override getSystemService(String) we cannot
3244         // perform a lookup by class alone.  We must first map the class to its
3245         // service name then invoke the string-based method.
3246         String serviceName = getSystemServiceName(serviceClass);
3247         return serviceName != null ? (T)getSystemService(serviceName) : null;
3248     }
3249 
3250     /**
3251      * Gets the name of the system-level service that is represented by the specified class.
3252      *
3253      * @param serviceClass The class of the desired service.
3254      * @return The service name or null if the class is not a supported system service.
3255      */
getSystemServiceName(@onNull Class<?> serviceClass)3256     public abstract @Nullable String getSystemServiceName(@NonNull Class<?> serviceClass);
3257 
3258     /**
3259      * Use with {@link #getSystemService(String)} to retrieve a
3260      * {@link android.os.PowerManager} for controlling power management,
3261      * including "wake locks," which let you keep the device on while
3262      * you're running long tasks.
3263      */
3264     public static final String POWER_SERVICE = "power";
3265 
3266     /**
3267      * Use with {@link #getSystemService(String)} to retrieve a
3268      * {@link android.os.RecoverySystem} for accessing the recovery system
3269      * service.
3270      *
3271      * @see #getSystemService(String)
3272      * @hide
3273      */
3274     public static final String RECOVERY_SERVICE = "recovery";
3275 
3276     /**
3277      * Use with {@link #getSystemService(String)} to retrieve a
3278      * {@link android.os.SystemUpdateManager} for accessing the system update
3279      * manager service.
3280      *
3281      * @see #getSystemService(String)
3282      * @hide
3283      */
3284     @SystemApi
3285     public static final String SYSTEM_UPDATE_SERVICE = "system_update";
3286 
3287     /**
3288      * Use with {@link #getSystemService(String)} to retrieve a
3289      * {@link android.view.WindowManager} for accessing the system's window
3290      * manager.
3291      *
3292      * @see #getSystemService(String)
3293      * @see android.view.WindowManager
3294      */
3295     public static final String WINDOW_SERVICE = "window";
3296 
3297     /**
3298      * Use with {@link #getSystemService(String)} to retrieve a
3299      * {@link android.view.LayoutInflater} for inflating layout resources in this
3300      * context.
3301      *
3302      * @see #getSystemService(String)
3303      * @see android.view.LayoutInflater
3304      */
3305     public static final String LAYOUT_INFLATER_SERVICE = "layout_inflater";
3306 
3307     /**
3308      * Use with {@link #getSystemService(String)} to retrieve a
3309      * {@link android.accounts.AccountManager} for receiving intents at a
3310      * time of your choosing.
3311      *
3312      * @see #getSystemService(String)
3313      * @see android.accounts.AccountManager
3314      */
3315     public static final String ACCOUNT_SERVICE = "account";
3316 
3317     /**
3318      * Use with {@link #getSystemService(String)} to retrieve a
3319      * {@link android.app.ActivityManager} for interacting with the global
3320      * system state.
3321      *
3322      * @see #getSystemService(String)
3323      * @see android.app.ActivityManager
3324      */
3325     public static final String ACTIVITY_SERVICE = "activity";
3326 
3327     /**
3328      * Use with {@link #getSystemService(String)} to retrieve a
3329      * {@link android.app.AlarmManager} for receiving intents at a
3330      * time of your choosing.
3331      *
3332      * @see #getSystemService(String)
3333      * @see android.app.AlarmManager
3334      */
3335     public static final String ALARM_SERVICE = "alarm";
3336 
3337     /**
3338      * Use with {@link #getSystemService(String)} to retrieve a
3339      * {@link android.app.NotificationManager} for informing the user of
3340      * background events.
3341      *
3342      * @see #getSystemService(String)
3343      * @see android.app.NotificationManager
3344      */
3345     public static final String NOTIFICATION_SERVICE = "notification";
3346 
3347     /**
3348      * Use with {@link #getSystemService(String)} to retrieve a
3349      * {@link android.view.accessibility.AccessibilityManager} for giving the user
3350      * feedback for UI events through the registered event listeners.
3351      *
3352      * @see #getSystemService(String)
3353      * @see android.view.accessibility.AccessibilityManager
3354      */
3355     public static final String ACCESSIBILITY_SERVICE = "accessibility";
3356 
3357     /**
3358      * Use with {@link #getSystemService(String)} to retrieve a
3359      * {@link android.view.accessibility.CaptioningManager} for obtaining
3360      * captioning properties and listening for changes in captioning
3361      * preferences.
3362      *
3363      * @see #getSystemService(String)
3364      * @see android.view.accessibility.CaptioningManager
3365      */
3366     public static final String CAPTIONING_SERVICE = "captioning";
3367 
3368     /**
3369      * Use with {@link #getSystemService(String)} to retrieve a
3370      * {@link android.app.NotificationManager} for controlling keyguard.
3371      *
3372      * @see #getSystemService(String)
3373      * @see android.app.KeyguardManager
3374      */
3375     public static final String KEYGUARD_SERVICE = "keyguard";
3376 
3377     /**
3378      * Use with {@link #getSystemService(String)} to retrieve a {@link
3379      * android.location.LocationManager} for controlling location
3380      * updates.
3381      *
3382      * @see #getSystemService(String)
3383      * @see android.location.LocationManager
3384      */
3385     public static final String LOCATION_SERVICE = "location";
3386 
3387     /**
3388      * Use with {@link #getSystemService(String)} to retrieve a
3389      * {@link android.location.CountryDetector} for detecting the country that
3390      * the user is in.
3391      *
3392      * @hide
3393      */
3394     public static final String COUNTRY_DETECTOR = "country_detector";
3395 
3396     /**
3397      * Use with {@link #getSystemService(String)} to retrieve a {@link
3398      * android.app.SearchManager} for handling searches.
3399      *
3400      * <p>
3401      * {@link Configuration#UI_MODE_TYPE_WATCH} does not support
3402      * {@link android.app.SearchManager}.
3403      *
3404      * @see #getSystemService
3405      * @see android.app.SearchManager
3406      */
3407     public static final String SEARCH_SERVICE = "search";
3408 
3409     /**
3410      * Use with {@link #getSystemService(String)} to retrieve a {@link
3411      * android.hardware.SensorManager} for accessing sensors.
3412      *
3413      * @see #getSystemService(String)
3414      * @see android.hardware.SensorManager
3415      */
3416     public static final String SENSOR_SERVICE = "sensor";
3417 
3418     /**
3419      * Use with {@link #getSystemService(String)} to retrieve a {@link
3420      * android.os.storage.StorageManager} for accessing system storage
3421      * functions.
3422      *
3423      * @see #getSystemService(String)
3424      * @see android.os.storage.StorageManager
3425      */
3426     public static final String STORAGE_SERVICE = "storage";
3427 
3428     /**
3429      * Use with {@link #getSystemService(String)} to retrieve a {@link
3430      * android.app.usage.StorageStatsManager} for accessing system storage
3431      * statistics.
3432      *
3433      * @see #getSystemService(String)
3434      * @see android.app.usage.StorageStatsManager
3435      */
3436     public static final String STORAGE_STATS_SERVICE = "storagestats";
3437 
3438     /**
3439      * Use with {@link #getSystemService(String)} to retrieve a
3440      * com.android.server.WallpaperService for accessing wallpapers.
3441      *
3442      * @see #getSystemService(String)
3443      */
3444     public static final String WALLPAPER_SERVICE = "wallpaper";
3445 
3446     /**
3447      * Use with {@link #getSystemService(String)} to retrieve a {@link
3448      * android.os.Vibrator} for interacting with the vibration hardware.
3449      *
3450      * @see #getSystemService(String)
3451      * @see android.os.Vibrator
3452      */
3453     public static final String VIBRATOR_SERVICE = "vibrator";
3454 
3455     /**
3456      * Use with {@link #getSystemService(String)} to retrieve a {@link
3457      * android.app.StatusBarManager} for interacting with the status bar.
3458      *
3459      * @see #getSystemService(String)
3460      * @see android.app.StatusBarManager
3461      * @hide
3462      */
3463     public static final String STATUS_BAR_SERVICE = "statusbar";
3464 
3465     /**
3466      * Use with {@link #getSystemService(String)} to retrieve a {@link
3467      * android.net.ConnectivityManager} for handling management of
3468      * network connections.
3469      *
3470      * @see #getSystemService(String)
3471      * @see android.net.ConnectivityManager
3472      */
3473     public static final String CONNECTIVITY_SERVICE = "connectivity";
3474 
3475     /**
3476      * Use with {@link #getSystemService(String)} to retrieve a
3477      * {@link android.net.IpSecManager} for encrypting Sockets or Networks with
3478      * IPSec.
3479      *
3480      * @see #getSystemService(String)
3481      */
3482     public static final String IPSEC_SERVICE = "ipsec";
3483 
3484     /**
3485      * Use with {@link #getSystemService(String)} to retrieve a {@link
3486      * android.os.IUpdateLock} for managing runtime sequences that
3487      * must not be interrupted by headless OTA application or similar.
3488      *
3489      * @hide
3490      * @see #getSystemService(String)
3491      * @see android.os.UpdateLock
3492      */
3493     public static final String UPDATE_LOCK_SERVICE = "updatelock";
3494 
3495     /**
3496      * Constant for the internal network management service, not really a Context service.
3497      * @hide
3498      */
3499     public static final String NETWORKMANAGEMENT_SERVICE = "network_management";
3500 
3501     /**
3502      * Use with {@link #getSystemService(String)} to retrieve a
3503      * {@link com.android.server.slice.SliceManagerService} for managing slices.
3504      * @hide
3505      * @see #getSystemService(String)
3506      */
3507     public static final String SLICE_SERVICE = "slice";
3508 
3509     /**
3510      * Use with {@link #getSystemService(String)} to retrieve a {@link
3511      * android.app.usage.NetworkStatsManager} for querying network usage stats.
3512      *
3513      * @see #getSystemService(String)
3514      * @see android.app.usage.NetworkStatsManager
3515      */
3516     public static final String NETWORK_STATS_SERVICE = "netstats";
3517     /** {@hide} */
3518     public static final String NETWORK_POLICY_SERVICE = "netpolicy";
3519     /** {@hide} */
3520     public static final String NETWORK_WATCHLIST_SERVICE = "network_watchlist";
3521 
3522     /**
3523      * Use with {@link #getSystemService(String)} to retrieve a {@link
3524      * android.net.wifi.WifiManager} for handling management of
3525      * Wi-Fi access.
3526      *
3527      * @see #getSystemService(String)
3528      * @see android.net.wifi.WifiManager
3529      */
3530     public static final String WIFI_SERVICE = "wifi";
3531 
3532     /**
3533      * Use with {@link #getSystemService(String)} to retrieve a {@link
3534      * android.net.wifi.p2p.WifiP2pManager} for handling management of
3535      * Wi-Fi peer-to-peer connections.
3536      *
3537      * @see #getSystemService(String)
3538      * @see android.net.wifi.p2p.WifiP2pManager
3539      */
3540     public static final String WIFI_P2P_SERVICE = "wifip2p";
3541 
3542     /**
3543      * Use with {@link #getSystemService(String)} to retrieve a
3544      * {@link android.net.wifi.aware.WifiAwareManager} for handling management of
3545      * Wi-Fi Aware.
3546      *
3547      * @see #getSystemService(String)
3548      * @see android.net.wifi.aware.WifiAwareManager
3549      */
3550     public static final String WIFI_AWARE_SERVICE = "wifiaware";
3551 
3552     /**
3553      * Use with {@link #getSystemService(String)} to retrieve a {@link
3554      * android.net.wifi.WifiScanner} for scanning the wifi universe
3555      *
3556      * @see #getSystemService(String)
3557      * @see android.net.wifi.WifiScanner
3558      * @hide
3559      */
3560     @SystemApi
3561     public static final String WIFI_SCANNING_SERVICE = "wifiscanner";
3562 
3563     /**
3564      * Use with {@link #getSystemService(String)} to retrieve a {@link
3565      * android.net.wifi.RttManager} for ranging devices with wifi
3566      *
3567      * @see #getSystemService(String)
3568      * @see android.net.wifi.RttManager
3569      * @hide
3570      */
3571     @SystemApi
3572     @Deprecated
3573     public static final String WIFI_RTT_SERVICE = "rttmanager";
3574 
3575     /**
3576      * Use with {@link #getSystemService(String)} to retrieve a {@link
3577      * android.net.wifi.rtt.WifiRttManager} for ranging devices with wifi
3578      *
3579      * Note: this is a replacement for WIFI_RTT_SERVICE above. It will
3580      * be renamed once final implementation in place.
3581      *
3582      * @see #getSystemService(String)
3583      * @see android.net.wifi.rtt.WifiRttManager
3584      */
3585     public static final String WIFI_RTT_RANGING_SERVICE = "wifirtt";
3586 
3587     /**
3588      * Use with {@link #getSystemService(String)} to retrieve a {@link
3589      * android.net.lowpan.LowpanManager} for handling management of
3590      * LoWPAN access.
3591      *
3592      * @see #getSystemService(String)
3593      * @see android.net.lowpan.LowpanManager
3594      *
3595      * @hide
3596      */
3597     public static final String LOWPAN_SERVICE = "lowpan";
3598 
3599     /**
3600      * Use with {@link #getSystemService(String)} to retrieve a {@link
3601      * android.net.EthernetManager} for handling management of
3602      * Ethernet access.
3603      *
3604      * @see #getSystemService(String)
3605      * @see android.net.EthernetManager
3606      *
3607      * @hide
3608      */
3609     public static final String ETHERNET_SERVICE = "ethernet";
3610 
3611     /**
3612      * Use with {@link #getSystemService(String)} to retrieve a {@link
3613      * android.net.nsd.NsdManager} for handling management of network service
3614      * discovery
3615      *
3616      * @see #getSystemService(String)
3617      * @see android.net.nsd.NsdManager
3618      */
3619     public static final String NSD_SERVICE = "servicediscovery";
3620 
3621     /**
3622      * Use with {@link #getSystemService(String)} to retrieve a
3623      * {@link android.media.AudioManager} for handling management of volume,
3624      * ringer modes and audio routing.
3625      *
3626      * @see #getSystemService(String)
3627      * @see android.media.AudioManager
3628      */
3629     public static final String AUDIO_SERVICE = "audio";
3630 
3631     /**
3632      * Use with {@link #getSystemService(String)} to retrieve a
3633      * {@link android.hardware.fingerprint.FingerprintManager} for handling management
3634      * of fingerprints.
3635      *
3636      * @see #getSystemService(String)
3637      * @see android.hardware.fingerprint.FingerprintManager
3638      */
3639     public static final String FINGERPRINT_SERVICE = "fingerprint";
3640 
3641     /**
3642      * Use with {@link #getSystemService(String)} to retrieve a
3643      * {@link android.media.MediaRouter} for controlling and managing
3644      * routing of media.
3645      *
3646      * @see #getSystemService(String)
3647      * @see android.media.MediaRouter
3648      */
3649     public static final String MEDIA_ROUTER_SERVICE = "media_router";
3650 
3651     /**
3652      * Use with {@link #getSystemService(String)} to retrieve a
3653      * {@link android.media.session.MediaSessionManager} for managing media Sessions.
3654      *
3655      * @see #getSystemService(String)
3656      * @see android.media.session.MediaSessionManager
3657      */
3658     public static final String MEDIA_SESSION_SERVICE = "media_session";
3659 
3660     /**
3661      * Use with {@link #getSystemService(String)} to retrieve a
3662      * {@link android.telephony.TelephonyManager} for handling management the
3663      * telephony features of the device.
3664      *
3665      * @see #getSystemService(String)
3666      * @see android.telephony.TelephonyManager
3667      */
3668     public static final String TELEPHONY_SERVICE = "phone";
3669 
3670     /**
3671      * Use with {@link #getSystemService(String)} to retrieve a
3672      * {@link android.telephony.SubscriptionManager} for handling management the
3673      * telephony subscriptions of the device.
3674      *
3675      * @see #getSystemService(String)
3676      * @see android.telephony.SubscriptionManager
3677      */
3678     public static final String TELEPHONY_SUBSCRIPTION_SERVICE = "telephony_subscription_service";
3679 
3680     /**
3681      * Use with {@link #getSystemService(String)} to retrieve a
3682      * {@link android.telecom.TelecomManager} to manage telecom-related features
3683      * of the device.
3684      *
3685      * @see #getSystemService(String)
3686      * @see android.telecom.TelecomManager
3687      */
3688     public static final String TELECOM_SERVICE = "telecom";
3689 
3690     /**
3691      * Use with {@link #getSystemService(String)} to retrieve a
3692      * {@link android.telephony.CarrierConfigManager} for reading carrier configuration values.
3693      *
3694      * @see #getSystemService(String)
3695      * @see android.telephony.CarrierConfigManager
3696      */
3697     public static final String CARRIER_CONFIG_SERVICE = "carrier_config";
3698 
3699     /**
3700      * Use with {@link #getSystemService(String)} to retrieve a
3701      * {@link android.telephony.euicc.EuiccManager} to manage the device eUICC (embedded SIM).
3702      *
3703      * @see #getSystemService(String)
3704      * @see android.telephony.euicc.EuiccManager
3705      */
3706     public static final String EUICC_SERVICE = "euicc";
3707 
3708     /**
3709      * Use with {@link #getSystemService(String)} to retrieve a
3710      * {@link android.telephony.euicc.EuiccCardManager} to access the device eUICC (embedded SIM).
3711      *
3712      * @see #getSystemService(String)
3713      * @see android.telephony.euicc.EuiccCardManager
3714      * @hide
3715      */
3716     @SystemApi
3717     public static final String EUICC_CARD_SERVICE = "euicc_card";
3718 
3719     /**
3720      * Use with {@link #getSystemService(String)} to retrieve a
3721      * {@link android.content.ClipboardManager} for accessing and modifying
3722      * the contents of the global clipboard.
3723      *
3724      * @see #getSystemService(String)
3725      * @see android.content.ClipboardManager
3726      */
3727     public static final String CLIPBOARD_SERVICE = "clipboard";
3728 
3729     /**
3730      * Use with {@link #getSystemService(String)} to retrieve a
3731      * {@link TextClassificationManager} for text classification services.
3732      *
3733      * @see #getSystemService(String)
3734      * @see TextClassificationManager
3735      */
3736     public static final String TEXT_CLASSIFICATION_SERVICE = "textclassification";
3737 
3738     /**
3739      * Use with {@link #getSystemService(String)} to retrieve a
3740      * {@link android.view.inputmethod.InputMethodManager} for accessing input
3741      * methods.
3742      *
3743      * @see #getSystemService(String)
3744      */
3745     public static final String INPUT_METHOD_SERVICE = "input_method";
3746 
3747     /**
3748      * Use with {@link #getSystemService(String)} to retrieve a
3749      * {@link android.view.textservice.TextServicesManager} for accessing
3750      * text services.
3751      *
3752      * @see #getSystemService(String)
3753      */
3754     public static final String TEXT_SERVICES_MANAGER_SERVICE = "textservices";
3755 
3756     /**
3757      * Use with {@link #getSystemService(String)} to retrieve a
3758      * {@link android.appwidget.AppWidgetManager} for accessing AppWidgets.
3759      *
3760      * @see #getSystemService(String)
3761      */
3762     public static final String APPWIDGET_SERVICE = "appwidget";
3763 
3764     /**
3765      * Official published name of the (internal) voice interaction manager service.
3766      *
3767      * @hide
3768      * @see #getSystemService(String)
3769      */
3770     public static final String VOICE_INTERACTION_MANAGER_SERVICE = "voiceinteraction";
3771 
3772     /**
3773      * Official published name of the (internal) autofill service.
3774      *
3775      * @hide
3776      * @see #getSystemService(String)
3777      */
3778     public static final String AUTOFILL_MANAGER_SERVICE = "autofill";
3779 
3780     /**
3781      * Use with {@link #getSystemService(String)} to access the
3782      * {@link com.android.server.voiceinteraction.SoundTriggerService}.
3783      *
3784      * @hide
3785      * @see #getSystemService(String)
3786      */
3787     public static final String SOUND_TRIGGER_SERVICE = "soundtrigger";
3788 
3789 
3790     /**
3791      * Use with {@link #getSystemService(String)} to retrieve an
3792      * {@link android.app.backup.IBackupManager IBackupManager} for communicating
3793      * with the backup mechanism.
3794      * @hide
3795      *
3796      * @see #getSystemService(String)
3797      */
3798     @SystemApi
3799     public static final String BACKUP_SERVICE = "backup";
3800 
3801     /**
3802      * Use with {@link #getSystemService(String)} to retrieve a
3803      * {@link android.os.DropBoxManager} instance for recording
3804      * diagnostic logs.
3805      * @see #getSystemService(String)
3806      */
3807     public static final String DROPBOX_SERVICE = "dropbox";
3808 
3809     /**
3810      * System service name for the DeviceIdleManager.
3811      * @see #getSystemService(String)
3812      * @hide
3813      */
3814     public static final String DEVICE_IDLE_CONTROLLER = "deviceidle";
3815 
3816     /**
3817      * Use with {@link #getSystemService(String)} to retrieve a
3818      * {@link android.app.admin.DevicePolicyManager} for working with global
3819      * device policy management.
3820      *
3821      * @see #getSystemService(String)
3822      */
3823     public static final String DEVICE_POLICY_SERVICE = "device_policy";
3824 
3825     /**
3826      * Use with {@link #getSystemService(String)} to retrieve a
3827      * {@link android.app.UiModeManager} for controlling UI modes.
3828      *
3829      * @see #getSystemService(String)
3830      */
3831     public static final String UI_MODE_SERVICE = "uimode";
3832 
3833     /**
3834      * Use with {@link #getSystemService(String)} to retrieve a
3835      * {@link android.app.DownloadManager} for requesting HTTP downloads.
3836      *
3837      * @see #getSystemService(String)
3838      */
3839     public static final String DOWNLOAD_SERVICE = "download";
3840 
3841     /**
3842      * Use with {@link #getSystemService(String)} to retrieve a
3843      * {@link android.os.BatteryManager} for managing battery state.
3844      *
3845      * @see #getSystemService(String)
3846      */
3847     public static final String BATTERY_SERVICE = "batterymanager";
3848 
3849     /**
3850      * Use with {@link #getSystemService(String)} to retrieve a
3851      * {@link android.nfc.NfcManager} for using NFC.
3852      *
3853      * @see #getSystemService(String)
3854      */
3855     public static final String NFC_SERVICE = "nfc";
3856 
3857     /**
3858      * Use with {@link #getSystemService(String)} to retrieve a
3859      * {@link android.bluetooth.BluetoothManager} for using Bluetooth.
3860      *
3861      * @see #getSystemService(String)
3862      */
3863     public static final String BLUETOOTH_SERVICE = "bluetooth";
3864 
3865     /**
3866      * Use with {@link #getSystemService(String)} to retrieve a
3867      * {@link android.net.sip.SipManager} for accessing the SIP related service.
3868      *
3869      * @see #getSystemService(String)
3870      */
3871     /** @hide */
3872     public static final String SIP_SERVICE = "sip";
3873 
3874     /**
3875      * Use with {@link #getSystemService(String)} to retrieve a {@link
3876      * android.hardware.usb.UsbManager} for access to USB devices (as a USB host)
3877      * and for controlling this device's behavior as a USB device.
3878      *
3879      * @see #getSystemService(String)
3880      * @see android.hardware.usb.UsbManager
3881      */
3882     public static final String USB_SERVICE = "usb";
3883 
3884     /**
3885      * Use with {@link #getSystemService(String)} to retrieve a {@link
3886      * android.hardware.SerialManager} for access to serial ports.
3887      *
3888      * @see #getSystemService(String)
3889      * @see android.hardware.SerialManager
3890      *
3891      * @hide
3892      */
3893     public static final String SERIAL_SERVICE = "serial";
3894 
3895     /**
3896      * Use with {@link #getSystemService(String)} to retrieve a
3897      * {@link android.hardware.hdmi.HdmiControlManager} for controlling and managing
3898      * HDMI-CEC protocol.
3899      *
3900      * @see #getSystemService(String)
3901      * @see android.hardware.hdmi.HdmiControlManager
3902      * @hide
3903      */
3904     @SystemApi
3905     public static final String HDMI_CONTROL_SERVICE = "hdmi_control";
3906 
3907     /**
3908      * Use with {@link #getSystemService(String)} to retrieve a
3909      * {@link android.hardware.input.InputManager} for interacting with input devices.
3910      *
3911      * @see #getSystemService(String)
3912      * @see android.hardware.input.InputManager
3913      */
3914     public static final String INPUT_SERVICE = "input";
3915 
3916     /**
3917      * Use with {@link #getSystemService(String)} to retrieve a
3918      * {@link android.hardware.display.DisplayManager} for interacting with display devices.
3919      *
3920      * @see #getSystemService(String)
3921      * @see android.hardware.display.DisplayManager
3922      */
3923     public static final String DISPLAY_SERVICE = "display";
3924 
3925     /**
3926      * Use with {@link #getSystemService(String)} to retrieve a
3927      * {@link android.os.UserManager} for managing users on devices that support multiple users.
3928      *
3929      * @see #getSystemService(String)
3930      * @see android.os.UserManager
3931      */
3932     public static final String USER_SERVICE = "user";
3933 
3934     /**
3935      * Use with {@link #getSystemService(String)} to retrieve a
3936      * {@link android.content.pm.LauncherApps} for querying and monitoring launchable apps across
3937      * profiles of a user.
3938      *
3939      * @see #getSystemService(String)
3940      * @see android.content.pm.LauncherApps
3941      */
3942     public static final String LAUNCHER_APPS_SERVICE = "launcherapps";
3943 
3944     /**
3945      * Use with {@link #getSystemService(String)} to retrieve a
3946      * {@link android.content.RestrictionsManager} for retrieving application restrictions
3947      * and requesting permissions for restricted operations.
3948      * @see #getSystemService(String)
3949      * @see android.content.RestrictionsManager
3950      */
3951     public static final String RESTRICTIONS_SERVICE = "restrictions";
3952 
3953     /**
3954      * Use with {@link #getSystemService(String)} to retrieve a
3955      * {@link android.app.AppOpsManager} for tracking application operations
3956      * on the device.
3957      *
3958      * @see #getSystemService(String)
3959      * @see android.app.AppOpsManager
3960      */
3961     public static final String APP_OPS_SERVICE = "appops";
3962 
3963     /**
3964      * Use with {@link #getSystemService(String)} to retrieve a
3965      * {@link android.hardware.camera2.CameraManager} for interacting with
3966      * camera devices.
3967      *
3968      * @see #getSystemService(String)
3969      * @see android.hardware.camera2.CameraManager
3970      */
3971     public static final String CAMERA_SERVICE = "camera";
3972 
3973     /**
3974      * {@link android.print.PrintManager} for printing and managing
3975      * printers and print tasks.
3976      *
3977      * @see #getSystemService(String)
3978      * @see android.print.PrintManager
3979      */
3980     public static final String PRINT_SERVICE = "print";
3981 
3982     /**
3983      * Use with {@link #getSystemService(String)} to retrieve a
3984      * {@link android.companion.CompanionDeviceManager} for managing companion devices
3985      *
3986      * @see #getSystemService(String)
3987      * @see android.companion.CompanionDeviceManager
3988      */
3989     public static final String COMPANION_DEVICE_SERVICE = "companiondevice";
3990 
3991     /**
3992      * Use with {@link #getSystemService(String)} to retrieve a
3993      * {@link android.hardware.ConsumerIrManager} for transmitting infrared
3994      * signals from the device.
3995      *
3996      * @see #getSystemService(String)
3997      * @see android.hardware.ConsumerIrManager
3998      */
3999     public static final String CONSUMER_IR_SERVICE = "consumer_ir";
4000 
4001     /**
4002      * {@link android.app.trust.TrustManager} for managing trust agents.
4003      * @see #getSystemService(String)
4004      * @see android.app.trust.TrustManager
4005      * @hide
4006      */
4007     public static final String TRUST_SERVICE = "trust";
4008 
4009     /**
4010      * Use with {@link #getSystemService(String)} to retrieve a
4011      * {@link android.media.tv.TvInputManager} for interacting with TV inputs
4012      * on the device.
4013      *
4014      * @see #getSystemService(String)
4015      * @see android.media.tv.TvInputManager
4016      */
4017     public static final String TV_INPUT_SERVICE = "tv_input";
4018 
4019     /**
4020      * {@link android.net.NetworkScoreManager} for managing network scoring.
4021      * @see #getSystemService(String)
4022      * @see android.net.NetworkScoreManager
4023      * @hide
4024      */
4025     @SystemApi
4026     public static final String NETWORK_SCORE_SERVICE = "network_score";
4027 
4028     /**
4029      * Use with {@link #getSystemService(String)} to retrieve a {@link
4030      * android.app.usage.UsageStatsManager} for querying device usage stats.
4031      *
4032      * @see #getSystemService(String)
4033      * @see android.app.usage.UsageStatsManager
4034      */
4035     public static final String USAGE_STATS_SERVICE = "usagestats";
4036 
4037     /**
4038      * Use with {@link #getSystemService(String)} to retrieve a {@link
4039      * android.app.job.JobScheduler} instance for managing occasional
4040      * background tasks.
4041      * @see #getSystemService(String)
4042      * @see android.app.job.JobScheduler
4043      */
4044     public static final String JOB_SCHEDULER_SERVICE = "jobscheduler";
4045 
4046     /**
4047      * Use with {@link #getSystemService(String)} to retrieve a {@link
4048      * android.service.persistentdata.PersistentDataBlockManager} instance
4049      * for interacting with a storage device that lives across factory resets.
4050      *
4051      * @see #getSystemService(String)
4052      * @see android.service.persistentdata.PersistentDataBlockManager
4053      * @hide
4054      */
4055     @SystemApi
4056     public static final String PERSISTENT_DATA_BLOCK_SERVICE = "persistent_data_block";
4057 
4058     /**
4059      * Use with {@link #getSystemService(String)} to retrieve a {@link
4060      * android.service.oemlock.OemLockManager} instance for managing the OEM lock.
4061      *
4062      * @see #getSystemService(String)
4063      * @see android.service.oemlock.OemLockManager
4064      * @hide
4065      */
4066     @SystemApi
4067     public static final String OEM_LOCK_SERVICE = "oem_lock";
4068 
4069     /**
4070      * Use with {@link #getSystemService(String)} to retrieve a {@link
4071      * android.media.projection.MediaProjectionManager} instance for managing
4072      * media projection sessions.
4073      * @see #getSystemService(String)
4074      * @see android.media.projection.MediaProjectionManager
4075      */
4076     public static final String MEDIA_PROJECTION_SERVICE = "media_projection";
4077 
4078     /**
4079      * Use with {@link #getSystemService(String)} to retrieve a
4080      * {@link android.media.midi.MidiManager} for accessing the MIDI service.
4081      *
4082      * @see #getSystemService(String)
4083      */
4084     public static final String MIDI_SERVICE = "midi";
4085 
4086 
4087     /**
4088      * Use with {@link #getSystemService(String)} to retrieve a
4089      * {@link android.hardware.radio.RadioManager} for accessing the broadcast radio service.
4090      *
4091      * @see #getSystemService(String)
4092      * @hide
4093      */
4094     public static final String RADIO_SERVICE = "broadcastradio";
4095 
4096     /**
4097      * Use with {@link #getSystemService(String)} to retrieve a
4098      * {@link android.os.HardwarePropertiesManager} for accessing the hardware properties service.
4099      *
4100      * @see #getSystemService(String)
4101      */
4102     public static final String HARDWARE_PROPERTIES_SERVICE = "hardware_properties";
4103 
4104     /**
4105      * Use with {@link #getSystemService(String)} to retrieve a
4106      * {@link android.content.pm.ShortcutManager} for accessing the launcher shortcut service.
4107      *
4108      * @see #getSystemService(String)
4109      * @see android.content.pm.ShortcutManager
4110      */
4111     public static final String SHORTCUT_SERVICE = "shortcut";
4112 
4113     /**
4114      * Use with {@link #getSystemService(String)} to retrieve a {@link
4115      * android.hardware.location.ContextHubManager} for accessing context hubs.
4116      *
4117      * @see #getSystemService(String)
4118      * @see android.hardware.location.ContextHubManager
4119      *
4120      * @hide
4121      */
4122     @SystemApi
4123     public static final String CONTEXTHUB_SERVICE = "contexthub";
4124 
4125     /**
4126      * Use with {@link #getSystemService(String)} to retrieve a
4127      * {@link android.os.health.SystemHealthManager} for accessing system health (battery, power,
4128      * memory, etc) metrics.
4129      *
4130      * @see #getSystemService(String)
4131      */
4132     public static final String SYSTEM_HEALTH_SERVICE = "systemhealth";
4133 
4134     /**
4135      * Gatekeeper Service.
4136      * @hide
4137      */
4138     public static final String GATEKEEPER_SERVICE = "android.service.gatekeeper.IGateKeeperService";
4139 
4140     /**
4141      * Service defining the policy for access to device identifiers.
4142      * @hide
4143      */
4144     public static final String DEVICE_IDENTIFIERS_SERVICE = "device_identifiers";
4145 
4146     /**
4147      * Service to report a system health "incident"
4148      * @hide
4149      */
4150     public static final String INCIDENT_SERVICE = "incident";
4151 
4152     /**
4153      * Service to assist statsd in obtaining general stats.
4154      * @hide
4155      */
4156     public static final String STATS_COMPANION_SERVICE = "statscompanion";
4157 
4158     /**
4159      * Use with {@link #getSystemService(String)} to retrieve an {@link android.app.StatsManager}.
4160      * @hide
4161      */
4162     @SystemApi
4163     public static final String STATS_MANAGER = "stats";
4164 
4165     /**
4166      * Use with {@link #getSystemService(String)} to retrieve a {@link
4167      * android.content.om.OverlayManager} for managing overlay packages.
4168      *
4169      * @see #getSystemService(String)
4170      * @see android.content.om.OverlayManager
4171      * @hide
4172      */
4173     public static final String OVERLAY_SERVICE = "overlay";
4174 
4175     /**
4176      * Use with {@link #getSystemService(String)} to retrieve a
4177      * {@link VrManager} for accessing the VR service.
4178      *
4179      * @see #getSystemService(String)
4180      * @hide
4181      */
4182     @SystemApi
4183     public static final String VR_SERVICE = "vrmanager";
4184 
4185     /**
4186      * Use with {@link #getSystemService(String)} to retrieve an
4187      * {@link android.app.timezone.ITimeZoneRulesManager}.
4188      * @hide
4189      *
4190      * @see #getSystemService(String)
4191      */
4192     public static final String TIME_ZONE_RULES_MANAGER_SERVICE = "timezone";
4193 
4194     /**
4195      * Use with {@link #getSystemService(String)} to retrieve a
4196      * {@link android.content.pm.CrossProfileApps} for cross profile operations.
4197      *
4198      * @see #getSystemService(String)
4199      */
4200     public static final String CROSS_PROFILE_APPS_SERVICE = "crossprofileapps";
4201 
4202     /**
4203      * Use with {@link #getSystemService} to retrieve a
4204      * {@link android.se.omapi.ISecureElementService}
4205      * for accessing the SecureElementService.
4206      *
4207      * @hide
4208      */
4209     @SystemApi
4210     public static final String SECURE_ELEMENT_SERVICE = "secure_element";
4211 
4212     /**
4213      * Determine whether the given permission is allowed for a particular
4214      * process and user ID running in the system.
4215      *
4216      * @param permission The name of the permission being checked.
4217      * @param pid The process ID being checked against.  Must be > 0.
4218      * @param uid The user ID being checked against.  A uid of 0 is the root
4219      * user, which will pass every permission check.
4220      *
4221      * @return {@link PackageManager#PERMISSION_GRANTED} if the given
4222      * pid/uid is allowed that permission, or
4223      * {@link PackageManager#PERMISSION_DENIED} if it is not.
4224      *
4225      * @see PackageManager#checkPermission(String, String)
4226      * @see #checkCallingPermission
4227      */
4228     @CheckResult(suggest="#enforcePermission(String,int,int,String)")
4229     @PackageManager.PermissionResult
checkPermission(@onNull String permission, int pid, int uid)4230     public abstract int checkPermission(@NonNull String permission, int pid, int uid);
4231 
4232     /** @hide */
4233     @PackageManager.PermissionResult
checkPermission(@onNull String permission, int pid, int uid, IBinder callerToken)4234     public abstract int checkPermission(@NonNull String permission, int pid, int uid,
4235             IBinder callerToken);
4236 
4237     /**
4238      * Determine whether the calling process of an IPC you are handling has been
4239      * granted a particular permission.  This is basically the same as calling
4240      * {@link #checkPermission(String, int, int)} with the pid and uid returned
4241      * by {@link android.os.Binder#getCallingPid} and
4242      * {@link android.os.Binder#getCallingUid}.  One important difference
4243      * is that if you are not currently processing an IPC, this function
4244      * will always fail.  This is done to protect against accidentally
4245      * leaking permissions; you can use {@link #checkCallingOrSelfPermission}
4246      * to avoid this protection.
4247      *
4248      * @param permission The name of the permission being checked.
4249      *
4250      * @return {@link PackageManager#PERMISSION_GRANTED} if the calling
4251      * pid/uid is allowed that permission, or
4252      * {@link PackageManager#PERMISSION_DENIED} if it is not.
4253      *
4254      * @see PackageManager#checkPermission(String, String)
4255      * @see #checkPermission
4256      * @see #checkCallingOrSelfPermission
4257      */
4258     @CheckResult(suggest="#enforceCallingPermission(String,String)")
4259     @PackageManager.PermissionResult
checkCallingPermission(@onNull String permission)4260     public abstract int checkCallingPermission(@NonNull String permission);
4261 
4262     /**
4263      * Determine whether the calling process of an IPC <em>or you</em> have been
4264      * granted a particular permission.  This is the same as
4265      * {@link #checkCallingPermission}, except it grants your own permissions
4266      * if you are not currently processing an IPC.  Use with care!
4267      *
4268      * @param permission The name of the permission being checked.
4269      *
4270      * @return {@link PackageManager#PERMISSION_GRANTED} if the calling
4271      * pid/uid is allowed that permission, or
4272      * {@link PackageManager#PERMISSION_DENIED} if it is not.
4273      *
4274      * @see PackageManager#checkPermission(String, String)
4275      * @see #checkPermission
4276      * @see #checkCallingPermission
4277      */
4278     @CheckResult(suggest="#enforceCallingOrSelfPermission(String,String)")
4279     @PackageManager.PermissionResult
checkCallingOrSelfPermission(@onNull String permission)4280     public abstract int checkCallingOrSelfPermission(@NonNull String permission);
4281 
4282     /**
4283      * Determine whether <em>you</em> have been granted a particular permission.
4284      *
4285      * @param permission The name of the permission being checked.
4286      *
4287      * @return {@link PackageManager#PERMISSION_GRANTED} if you have the
4288      * permission, or {@link PackageManager#PERMISSION_DENIED} if not.
4289      *
4290      * @see PackageManager#checkPermission(String, String)
4291      * @see #checkCallingPermission(String)
4292      */
4293     @PackageManager.PermissionResult
checkSelfPermission(@onNull String permission)4294     public abstract int checkSelfPermission(@NonNull String permission);
4295 
4296     /**
4297      * If the given permission is not allowed for a particular process
4298      * and user ID running in the system, throw a {@link SecurityException}.
4299      *
4300      * @param permission The name of the permission being checked.
4301      * @param pid The process ID being checked against.  Must be &gt; 0.
4302      * @param uid The user ID being checked against.  A uid of 0 is the root
4303      * user, which will pass every permission check.
4304      * @param message A message to include in the exception if it is thrown.
4305      *
4306      * @see #checkPermission(String, int, int)
4307      */
enforcePermission( @onNull String permission, int pid, int uid, @Nullable String message)4308     public abstract void enforcePermission(
4309             @NonNull String permission, int pid, int uid, @Nullable String message);
4310 
4311     /**
4312      * If the calling process of an IPC you are handling has not been
4313      * granted a particular permission, throw a {@link
4314      * SecurityException}.  This is basically the same as calling
4315      * {@link #enforcePermission(String, int, int, String)} with the
4316      * pid and uid returned by {@link android.os.Binder#getCallingPid}
4317      * and {@link android.os.Binder#getCallingUid}.  One important
4318      * difference is that if you are not currently processing an IPC,
4319      * this function will always throw the SecurityException.  This is
4320      * done to protect against accidentally leaking permissions; you
4321      * can use {@link #enforceCallingOrSelfPermission} to avoid this
4322      * protection.
4323      *
4324      * @param permission The name of the permission being checked.
4325      * @param message A message to include in the exception if it is thrown.
4326      *
4327      * @see #checkCallingPermission(String)
4328      */
enforceCallingPermission( @onNull String permission, @Nullable String message)4329     public abstract void enforceCallingPermission(
4330             @NonNull String permission, @Nullable String message);
4331 
4332     /**
4333      * If neither you nor the calling process of an IPC you are
4334      * handling has been granted a particular permission, throw a
4335      * {@link SecurityException}.  This is the same as {@link
4336      * #enforceCallingPermission}, except it grants your own
4337      * permissions if you are not currently processing an IPC.  Use
4338      * with care!
4339      *
4340      * @param permission The name of the permission being checked.
4341      * @param message A message to include in the exception if it is thrown.
4342      *
4343      * @see #checkCallingOrSelfPermission(String)
4344      */
enforceCallingOrSelfPermission( @onNull String permission, @Nullable String message)4345     public abstract void enforceCallingOrSelfPermission(
4346             @NonNull String permission, @Nullable String message);
4347 
4348     /**
4349      * Grant permission to access a specific Uri to another package, regardless
4350      * of whether that package has general permission to access the Uri's
4351      * content provider.  This can be used to grant specific, temporary
4352      * permissions, typically in response to user interaction (such as the
4353      * user opening an attachment that you would like someone else to
4354      * display).
4355      *
4356      * <p>Normally you should use {@link Intent#FLAG_GRANT_READ_URI_PERMISSION
4357      * Intent.FLAG_GRANT_READ_URI_PERMISSION} or
4358      * {@link Intent#FLAG_GRANT_WRITE_URI_PERMISSION
4359      * Intent.FLAG_GRANT_WRITE_URI_PERMISSION} with the Intent being used to
4360      * start an activity instead of this function directly.  If you use this
4361      * function directly, you should be sure to call
4362      * {@link #revokeUriPermission} when the target should no longer be allowed
4363      * to access it.
4364      *
4365      * <p>To succeed, the content provider owning the Uri must have set the
4366      * {@link android.R.styleable#AndroidManifestProvider_grantUriPermissions
4367      * grantUriPermissions} attribute in its manifest or included the
4368      * {@link android.R.styleable#AndroidManifestGrantUriPermission
4369      * &lt;grant-uri-permissions&gt;} tag.
4370      *
4371      * @param toPackage The package you would like to allow to access the Uri.
4372      * @param uri The Uri you would like to grant access to.
4373      * @param modeFlags The desired access modes.
4374      *
4375      * @see #revokeUriPermission
4376      */
grantUriPermission(String toPackage, Uri uri, @Intent.GrantUriMode int modeFlags)4377     public abstract void grantUriPermission(String toPackage, Uri uri,
4378             @Intent.GrantUriMode int modeFlags);
4379 
4380     /**
4381      * Remove all permissions to access a particular content provider Uri
4382      * that were previously added with {@link #grantUriPermission} or <em>any other</em> mechanism.
4383      * The given Uri will match all previously granted Uris that are the same or a
4384      * sub-path of the given Uri.  That is, revoking "content://foo/target" will
4385      * revoke both "content://foo/target" and "content://foo/target/sub", but not
4386      * "content://foo".  It will not remove any prefix grants that exist at a
4387      * higher level.
4388      *
4389      * <p>Prior to {@link android.os.Build.VERSION_CODES#LOLLIPOP}, if you did not have
4390      * regular permission access to a Uri, but had received access to it through
4391      * a specific Uri permission grant, you could not revoke that grant with this
4392      * function and a {@link SecurityException} would be thrown.  As of
4393      * {@link android.os.Build.VERSION_CODES#LOLLIPOP}, this function will not throw a security
4394      * exception, but will remove whatever permission grants to the Uri had been given to the app
4395      * (or none).</p>
4396      *
4397      * <p>Unlike {@link #revokeUriPermission(String, Uri, int)}, this method impacts all permission
4398      * grants matching the given Uri, for any package they had been granted to, through any
4399      * mechanism this had happened (such as indirectly through the clipboard, activity launch,
4400      * service start, etc).  That means this can be potentially dangerous to use, as it can
4401      * revoke grants that another app could be strongly expecting to stick around.</p>
4402      *
4403      * @param uri The Uri you would like to revoke access to.
4404      * @param modeFlags The access modes to revoke.
4405      *
4406      * @see #grantUriPermission
4407      */
revokeUriPermission(Uri uri, @Intent.AccessUriMode int modeFlags)4408     public abstract void revokeUriPermission(Uri uri, @Intent.AccessUriMode int modeFlags);
4409 
4410     /**
4411      * Remove permissions to access a particular content provider Uri
4412      * that were previously added with {@link #grantUriPermission} for a specific target
4413      * package.  The given Uri will match all previously granted Uris that are the same or a
4414      * sub-path of the given Uri.  That is, revoking "content://foo/target" will
4415      * revoke both "content://foo/target" and "content://foo/target/sub", but not
4416      * "content://foo".  It will not remove any prefix grants that exist at a
4417      * higher level.
4418      *
4419      * <p>Unlike {@link #revokeUriPermission(Uri, int)}, this method will <em>only</em>
4420      * revoke permissions that had been explicitly granted through {@link #grantUriPermission}
4421      * and only for the package specified.  Any matching grants that have happened through
4422      * other mechanisms (clipboard, activity launching, service starting, etc) will not be
4423      * removed.</p>
4424      *
4425      * @param toPackage The package you had previously granted access to.
4426      * @param uri The Uri you would like to revoke access to.
4427      * @param modeFlags The access modes to revoke.
4428      *
4429      * @see #grantUriPermission
4430      */
revokeUriPermission(String toPackage, Uri uri, @Intent.AccessUriMode int modeFlags)4431     public abstract void revokeUriPermission(String toPackage, Uri uri,
4432             @Intent.AccessUriMode int modeFlags);
4433 
4434     /**
4435      * Determine whether a particular process and user ID has been granted
4436      * permission to access a specific URI.  This only checks for permissions
4437      * that have been explicitly granted -- if the given process/uid has
4438      * more general access to the URI's content provider then this check will
4439      * always fail.
4440      *
4441      * @param uri The uri that is being checked.
4442      * @param pid The process ID being checked against.  Must be &gt; 0.
4443      * @param uid The user ID being checked against.  A uid of 0 is the root
4444      * user, which will pass every permission check.
4445      * @param modeFlags The access modes to check.
4446      *
4447      * @return {@link PackageManager#PERMISSION_GRANTED} if the given
4448      * pid/uid is allowed to access that uri, or
4449      * {@link PackageManager#PERMISSION_DENIED} if it is not.
4450      *
4451      * @see #checkCallingUriPermission
4452      */
4453     @CheckResult(suggest="#enforceUriPermission(Uri,int,int,String)")
4454     @PackageManager.PermissionResult
checkUriPermission(Uri uri, int pid, int uid, @Intent.AccessUriMode int modeFlags)4455     public abstract int checkUriPermission(Uri uri, int pid, int uid,
4456             @Intent.AccessUriMode int modeFlags);
4457 
4458     /** @hide */
4459     @PackageManager.PermissionResult
checkUriPermission(Uri uri, int pid, int uid, @Intent.AccessUriMode int modeFlags, IBinder callerToken)4460     public abstract int checkUriPermission(Uri uri, int pid, int uid,
4461             @Intent.AccessUriMode int modeFlags, IBinder callerToken);
4462 
4463     /**
4464      * Determine whether the calling process and user ID has been
4465      * granted permission to access a specific URI.  This is basically
4466      * the same as calling {@link #checkUriPermission(Uri, int, int,
4467      * int)} with the pid and uid returned by {@link
4468      * android.os.Binder#getCallingPid} and {@link
4469      * android.os.Binder#getCallingUid}.  One important difference is
4470      * that if you are not currently processing an IPC, this function
4471      * will always fail.
4472      *
4473      * @param uri The uri that is being checked.
4474      * @param modeFlags The access modes to check.
4475      *
4476      * @return {@link PackageManager#PERMISSION_GRANTED} if the caller
4477      * is allowed to access that uri, or
4478      * {@link PackageManager#PERMISSION_DENIED} if it is not.
4479      *
4480      * @see #checkUriPermission(Uri, int, int, int)
4481      */
4482     @CheckResult(suggest="#enforceCallingUriPermission(Uri,int,String)")
4483     @PackageManager.PermissionResult
checkCallingUriPermission(Uri uri, @Intent.AccessUriMode int modeFlags)4484     public abstract int checkCallingUriPermission(Uri uri, @Intent.AccessUriMode int modeFlags);
4485 
4486     /**
4487      * Determine whether the calling process of an IPC <em>or you</em> has been granted
4488      * permission to access a specific URI.  This is the same as
4489      * {@link #checkCallingUriPermission}, except it grants your own permissions
4490      * if you are not currently processing an IPC.  Use with care!
4491      *
4492      * @param uri The uri that is being checked.
4493      * @param modeFlags The access modes to check.
4494      *
4495      * @return {@link PackageManager#PERMISSION_GRANTED} if the caller
4496      * is allowed to access that uri, or
4497      * {@link PackageManager#PERMISSION_DENIED} if it is not.
4498      *
4499      * @see #checkCallingUriPermission
4500      */
4501     @CheckResult(suggest="#enforceCallingOrSelfUriPermission(Uri,int,String)")
4502     @PackageManager.PermissionResult
checkCallingOrSelfUriPermission(Uri uri, @Intent.AccessUriMode int modeFlags)4503     public abstract int checkCallingOrSelfUriPermission(Uri uri,
4504             @Intent.AccessUriMode int modeFlags);
4505 
4506     /**
4507      * Check both a Uri and normal permission.  This allows you to perform
4508      * both {@link #checkPermission} and {@link #checkUriPermission} in one
4509      * call.
4510      *
4511      * @param uri The Uri whose permission is to be checked, or null to not
4512      * do this check.
4513      * @param readPermission The permission that provides overall read access,
4514      * or null to not do this check.
4515      * @param writePermission The permission that provides overall write
4516      * access, or null to not do this check.
4517      * @param pid The process ID being checked against.  Must be &gt; 0.
4518      * @param uid The user ID being checked against.  A uid of 0 is the root
4519      * user, which will pass every permission check.
4520      * @param modeFlags The access modes to check.
4521      *
4522      * @return {@link PackageManager#PERMISSION_GRANTED} if the caller
4523      * is allowed to access that uri or holds one of the given permissions, or
4524      * {@link PackageManager#PERMISSION_DENIED} if it is not.
4525      */
4526     @CheckResult(suggest="#enforceUriPermission(Uri,String,String,int,int,int,String)")
4527     @PackageManager.PermissionResult
checkUriPermission(@ullable Uri uri, @Nullable String readPermission, @Nullable String writePermission, int pid, int uid, @Intent.AccessUriMode int modeFlags)4528     public abstract int checkUriPermission(@Nullable Uri uri, @Nullable String readPermission,
4529             @Nullable String writePermission, int pid, int uid,
4530             @Intent.AccessUriMode int modeFlags);
4531 
4532     /**
4533      * If a particular process and user ID has not been granted
4534      * permission to access a specific URI, throw {@link
4535      * SecurityException}.  This only checks for permissions that have
4536      * been explicitly granted -- if the given process/uid has more
4537      * general access to the URI's content provider then this check
4538      * will always fail.
4539      *
4540      * @param uri The uri that is being checked.
4541      * @param pid The process ID being checked against.  Must be &gt; 0.
4542      * @param uid The user ID being checked against.  A uid of 0 is the root
4543      * user, which will pass every permission check.
4544      * @param modeFlags The access modes to enforce.
4545      * @param message A message to include in the exception if it is thrown.
4546      *
4547      * @see #checkUriPermission(Uri, int, int, int)
4548      */
enforceUriPermission( Uri uri, int pid, int uid, @Intent.AccessUriMode int modeFlags, String message)4549     public abstract void enforceUriPermission(
4550             Uri uri, int pid, int uid, @Intent.AccessUriMode int modeFlags, String message);
4551 
4552     /**
4553      * If the calling process and user ID has not been granted
4554      * permission to access a specific URI, throw {@link
4555      * SecurityException}.  This is basically the same as calling
4556      * {@link #enforceUriPermission(Uri, int, int, int, String)} with
4557      * the pid and uid returned by {@link
4558      * android.os.Binder#getCallingPid} and {@link
4559      * android.os.Binder#getCallingUid}.  One important difference is
4560      * that if you are not currently processing an IPC, this function
4561      * will always throw a SecurityException.
4562      *
4563      * @param uri The uri that is being checked.
4564      * @param modeFlags The access modes to enforce.
4565      * @param message A message to include in the exception if it is thrown.
4566      *
4567      * @see #checkCallingUriPermission(Uri, int)
4568      */
enforceCallingUriPermission( Uri uri, @Intent.AccessUriMode int modeFlags, String message)4569     public abstract void enforceCallingUriPermission(
4570             Uri uri, @Intent.AccessUriMode int modeFlags, String message);
4571 
4572     /**
4573      * If the calling process of an IPC <em>or you</em> has not been
4574      * granted permission to access a specific URI, throw {@link
4575      * SecurityException}.  This is the same as {@link
4576      * #enforceCallingUriPermission}, except it grants your own
4577      * permissions if you are not currently processing an IPC.  Use
4578      * with care!
4579      *
4580      * @param uri The uri that is being checked.
4581      * @param modeFlags The access modes to enforce.
4582      * @param message A message to include in the exception if it is thrown.
4583      *
4584      * @see #checkCallingOrSelfUriPermission(Uri, int)
4585      */
enforceCallingOrSelfUriPermission( Uri uri, @Intent.AccessUriMode int modeFlags, String message)4586     public abstract void enforceCallingOrSelfUriPermission(
4587             Uri uri, @Intent.AccessUriMode int modeFlags, String message);
4588 
4589     /**
4590      * Enforce both a Uri and normal permission.  This allows you to perform
4591      * both {@link #enforcePermission} and {@link #enforceUriPermission} in one
4592      * call.
4593      *
4594      * @param uri The Uri whose permission is to be checked, or null to not
4595      * do this check.
4596      * @param readPermission The permission that provides overall read access,
4597      * or null to not do this check.
4598      * @param writePermission The permission that provides overall write
4599      * access, or null to not do this check.
4600      * @param pid The process ID being checked against.  Must be &gt; 0.
4601      * @param uid The user ID being checked against.  A uid of 0 is the root
4602      * user, which will pass every permission check.
4603      * @param modeFlags The access modes to enforce.
4604      * @param message A message to include in the exception if it is thrown.
4605      *
4606      * @see #checkUriPermission(Uri, String, String, int, int, int)
4607      */
enforceUriPermission( @ullable Uri uri, @Nullable String readPermission, @Nullable String writePermission, int pid, int uid, @Intent.AccessUriMode int modeFlags, @Nullable String message)4608     public abstract void enforceUriPermission(
4609             @Nullable Uri uri, @Nullable String readPermission,
4610             @Nullable String writePermission, int pid, int uid, @Intent.AccessUriMode int modeFlags,
4611             @Nullable String message);
4612 
4613     /** @hide */
4614     @IntDef(flag = true, prefix = { "CONTEXT_" }, value = {
4615             CONTEXT_INCLUDE_CODE,
4616             CONTEXT_IGNORE_SECURITY,
4617             CONTEXT_RESTRICTED,
4618             CONTEXT_DEVICE_PROTECTED_STORAGE,
4619             CONTEXT_CREDENTIAL_PROTECTED_STORAGE,
4620             CONTEXT_REGISTER_PACKAGE,
4621     })
4622     @Retention(RetentionPolicy.SOURCE)
4623     public @interface CreatePackageOptions {}
4624 
4625     /**
4626      * Flag for use with {@link #createPackageContext}: include the application
4627      * code with the context.  This means loading code into the caller's
4628      * process, so that {@link #getClassLoader()} can be used to instantiate
4629      * the application's classes.  Setting this flags imposes security
4630      * restrictions on what application context you can access; if the
4631      * requested application can not be safely loaded into your process,
4632      * java.lang.SecurityException will be thrown.  If this flag is not set,
4633      * there will be no restrictions on the packages that can be loaded,
4634      * but {@link #getClassLoader} will always return the default system
4635      * class loader.
4636      */
4637     public static final int CONTEXT_INCLUDE_CODE = 0x00000001;
4638 
4639     /**
4640      * Flag for use with {@link #createPackageContext}: ignore any security
4641      * restrictions on the Context being requested, allowing it to always
4642      * be loaded.  For use with {@link #CONTEXT_INCLUDE_CODE} to allow code
4643      * to be loaded into a process even when it isn't safe to do so.  Use
4644      * with extreme care!
4645      */
4646     public static final int CONTEXT_IGNORE_SECURITY = 0x00000002;
4647 
4648     /**
4649      * Flag for use with {@link #createPackageContext}: a restricted context may
4650      * disable specific features. For instance, a View associated with a restricted
4651      * context would ignore particular XML attributes.
4652      */
4653     public static final int CONTEXT_RESTRICTED = 0x00000004;
4654 
4655     /**
4656      * Flag for use with {@link #createPackageContext}: point all file APIs at
4657      * device-protected storage.
4658      *
4659      * @hide
4660      */
4661     public static final int CONTEXT_DEVICE_PROTECTED_STORAGE = 0x00000008;
4662 
4663     /**
4664      * Flag for use with {@link #createPackageContext}: point all file APIs at
4665      * credential-protected storage.
4666      *
4667      * @hide
4668      */
4669     public static final int CONTEXT_CREDENTIAL_PROTECTED_STORAGE = 0x00000010;
4670 
4671     /**
4672      * @hide Used to indicate we should tell the activity manager about the process
4673      * loading this code.
4674      */
4675     public static final int CONTEXT_REGISTER_PACKAGE = 0x40000000;
4676 
4677     /**
4678      * Return a new Context object for the given application name.  This
4679      * Context is the same as what the named application gets when it is
4680      * launched, containing the same resources and class loader.  Each call to
4681      * this method returns a new instance of a Context object; Context objects
4682      * are not shared, however they share common state (Resources, ClassLoader,
4683      * etc) so the Context instance itself is fairly lightweight.
4684      *
4685      * <p>Throws {@link android.content.pm.PackageManager.NameNotFoundException} if there is no
4686      * application with the given package name.
4687      *
4688      * <p>Throws {@link java.lang.SecurityException} if the Context requested
4689      * can not be loaded into the caller's process for security reasons (see
4690      * {@link #CONTEXT_INCLUDE_CODE} for more information}.
4691      *
4692      * @param packageName Name of the application's package.
4693      * @param flags Option flags.
4694      *
4695      * @return A {@link Context} for the application.
4696      *
4697      * @throws SecurityException &nbsp;
4698      * @throws PackageManager.NameNotFoundException if there is no application with
4699      * the given package name.
4700      */
createPackageContext(String packageName, @CreatePackageOptions int flags)4701     public abstract Context createPackageContext(String packageName,
4702             @CreatePackageOptions int flags) throws PackageManager.NameNotFoundException;
4703 
4704     /**
4705      * Similar to {@link #createPackageContext(String, int)}, but with a
4706      * different {@link UserHandle}. For example, {@link #getContentResolver()}
4707      * will open any {@link Uri} as the given user.
4708      *
4709      * @hide
4710      */
4711     @SystemApi
createPackageContextAsUser( String packageName, @CreatePackageOptions int flags, UserHandle user)4712     public Context createPackageContextAsUser(
4713             String packageName, @CreatePackageOptions int flags, UserHandle user)
4714             throws PackageManager.NameNotFoundException {
4715         if (Build.IS_ENG) {
4716             throw new IllegalStateException("createPackageContextAsUser not overridden!");
4717         }
4718         return this;
4719     }
4720 
4721     /**
4722      * Creates a context given an {@link android.content.pm.ApplicationInfo}.
4723      *
4724      * @hide
4725      */
createApplicationContext(ApplicationInfo application, @CreatePackageOptions int flags)4726     public abstract Context createApplicationContext(ApplicationInfo application,
4727             @CreatePackageOptions int flags) throws PackageManager.NameNotFoundException;
4728 
4729     /**
4730      * Return a new Context object for the given split name. The new Context has a ClassLoader and
4731      * Resources object that can access the split's and all of its dependencies' code/resources.
4732      * Each call to this method returns a new instance of a Context object;
4733      * Context objects are not shared, however common state (ClassLoader, other Resources for
4734      * the same split) may be so the Context itself can be fairly lightweight.
4735      *
4736      * @param splitName The name of the split to include, as declared in the split's
4737      *                  <code>AndroidManifest.xml</code>.
4738      * @return A {@link Context} with the given split's code and/or resources loaded.
4739      */
createContextForSplit(String splitName)4740     public abstract Context createContextForSplit(String splitName)
4741             throws PackageManager.NameNotFoundException;
4742 
4743     /**
4744      * Get the user associated with this context
4745      * @hide
4746      */
4747     @TestApi
getUser()4748     public UserHandle getUser() {
4749         return android.os.Process.myUserHandle();
4750     }
4751 
4752     /**
4753      * Get the user associated with this context
4754      * @hide
4755      */
4756     @TestApi
getUserId()4757     public @UserIdInt int getUserId() {
4758         return android.os.UserHandle.myUserId();
4759     }
4760 
4761     /**
4762      * Return a new Context object for the current Context but whose resources
4763      * are adjusted to match the given Configuration.  Each call to this method
4764      * returns a new instance of a Context object; Context objects are not
4765      * shared, however common state (ClassLoader, other Resources for the
4766      * same configuration) may be so the Context itself can be fairly lightweight.
4767      *
4768      * @param overrideConfiguration A {@link Configuration} specifying what
4769      * values to modify in the base Configuration of the original Context's
4770      * resources.  If the base configuration changes (such as due to an
4771      * orientation change), the resources of this context will also change except
4772      * for those that have been explicitly overridden with a value here.
4773      *
4774      * @return A {@link Context} with the given configuration override.
4775      */
createConfigurationContext( @onNull Configuration overrideConfiguration)4776     public abstract Context createConfigurationContext(
4777             @NonNull Configuration overrideConfiguration);
4778 
4779     /**
4780      * Return a new Context object for the current Context but whose resources
4781      * are adjusted to match the metrics of the given Display.  Each call to this method
4782      * returns a new instance of a Context object; Context objects are not
4783      * shared, however common state (ClassLoader, other Resources for the
4784      * same configuration) may be so the Context itself can be fairly lightweight.
4785      *
4786      * The returned display Context provides a {@link WindowManager}
4787      * (see {@link #getSystemService(String)}) that is configured to show windows
4788      * on the given display.  The WindowManager's {@link WindowManager#getDefaultDisplay}
4789      * method can be used to retrieve the Display from the returned Context.
4790      *
4791      * @param display A {@link Display} object specifying the display
4792      * for whose metrics the Context's resources should be tailored and upon which
4793      * new windows should be shown.
4794      *
4795      * @return A {@link Context} for the display.
4796      */
createDisplayContext(@onNull Display display)4797     public abstract Context createDisplayContext(@NonNull Display display);
4798 
4799     /**
4800      * Return a new Context object for the current Context but whose storage
4801      * APIs are backed by device-protected storage.
4802      * <p>
4803      * On devices with direct boot, data stored in this location is encrypted
4804      * with a key tied to the physical device, and it can be accessed
4805      * immediately after the device has booted successfully, both
4806      * <em>before and after</em> the user has authenticated with their
4807      * credentials (such as a lock pattern or PIN).
4808      * <p>
4809      * Because device-protected data is available without user authentication,
4810      * you should carefully limit the data you store using this Context. For
4811      * example, storing sensitive authentication tokens or passwords in the
4812      * device-protected area is strongly discouraged.
4813      * <p>
4814      * If the underlying device does not have the ability to store
4815      * device-protected and credential-protected data using different keys, then
4816      * both storage areas will become available at the same time. They remain as
4817      * two distinct storage locations on disk, and only the window of
4818      * availability changes.
4819      * <p>
4820      * Each call to this method returns a new instance of a Context object;
4821      * Context objects are not shared, however common state (ClassLoader, other
4822      * Resources for the same configuration) may be so the Context itself can be
4823      * fairly lightweight.
4824      *
4825      * @see #isDeviceProtectedStorage()
4826      */
createDeviceProtectedStorageContext()4827     public abstract Context createDeviceProtectedStorageContext();
4828 
4829     /**
4830      * Return a new Context object for the current Context but whose storage
4831      * APIs are backed by credential-protected storage. This is the default
4832      * storage area for apps unless
4833      * {@link android.R.attr#defaultToDeviceProtectedStorage} was requested.
4834      * <p>
4835      * On devices with direct boot, data stored in this location is encrypted
4836      * with a key tied to user credentials, which can be accessed
4837      * <em>only after</em> the user has entered their credentials (such as a
4838      * lock pattern or PIN).
4839      * <p>
4840      * If the underlying device does not have the ability to store
4841      * device-protected and credential-protected data using different keys, then
4842      * both storage areas will become available at the same time. They remain as
4843      * two distinct storage locations on disk, and only the window of
4844      * availability changes.
4845      * <p>
4846      * Each call to this method returns a new instance of a Context object;
4847      * Context objects are not shared, however common state (ClassLoader, other
4848      * Resources for the same configuration) may be so the Context itself can be
4849      * fairly lightweight.
4850      *
4851      * @see #isCredentialProtectedStorage()
4852      * @hide
4853      */
4854     @SystemApi
createCredentialProtectedStorageContext()4855     public abstract Context createCredentialProtectedStorageContext();
4856 
4857     /**
4858      * Gets the display adjustments holder for this context.  This information
4859      * is provided on a per-application or activity basis and is used to simulate lower density
4860      * display metrics for legacy applications and restricted screen sizes.
4861      *
4862      * @param displayId The display id for which to get compatibility info.
4863      * @return The compatibility info holder, or null if not required by the application.
4864      * @hide
4865      */
getDisplayAdjustments(int displayId)4866     public abstract DisplayAdjustments getDisplayAdjustments(int displayId);
4867 
4868     /**
4869      * @hide
4870      */
getDisplay()4871     public abstract Display getDisplay();
4872 
4873     /**
4874      * @hide
4875      */
updateDisplay(int displayId)4876     public abstract void updateDisplay(int displayId);
4877 
4878     /**
4879      * Indicates whether this Context is restricted.
4880      *
4881      * @return {@code true} if this Context is restricted, {@code false} otherwise.
4882      *
4883      * @see #CONTEXT_RESTRICTED
4884      */
isRestricted()4885     public boolean isRestricted() {
4886         return false;
4887     }
4888 
4889     /**
4890      * Indicates if the storage APIs of this Context are backed by
4891      * device-protected storage.
4892      *
4893      * @see #createDeviceProtectedStorageContext()
4894      */
isDeviceProtectedStorage()4895     public abstract boolean isDeviceProtectedStorage();
4896 
4897     /**
4898      * Indicates if the storage APIs of this Context are backed by
4899      * credential-protected storage.
4900      *
4901      * @see #createCredentialProtectedStorageContext()
4902      * @hide
4903      */
4904     @SystemApi
isCredentialProtectedStorage()4905     public abstract boolean isCredentialProtectedStorage();
4906 
4907     /**
4908      * Returns true if the context can load unsafe resources, e.g. fonts.
4909      * @hide
4910      */
canLoadUnsafeResources()4911     public abstract boolean canLoadUnsafeResources();
4912 
4913     /**
4914      * @hide
4915      */
getActivityToken()4916     public IBinder getActivityToken() {
4917         throw new RuntimeException("Not implemented. Must override in a subclass.");
4918     }
4919 
4920     /**
4921      * @hide
4922      */
4923     @Nullable
getServiceDispatcher(ServiceConnection conn, Handler handler, int flags)4924     public IServiceConnection getServiceDispatcher(ServiceConnection conn, Handler handler,
4925             int flags) {
4926         throw new RuntimeException("Not implemented. Must override in a subclass.");
4927     }
4928 
4929     /**
4930      * @hide
4931      */
getIApplicationThread()4932     public IApplicationThread getIApplicationThread() {
4933         throw new RuntimeException("Not implemented. Must override in a subclass.");
4934     }
4935 
4936     /**
4937      * @hide
4938      */
getMainThreadHandler()4939     public Handler getMainThreadHandler() {
4940         throw new RuntimeException("Not implemented. Must override in a subclass.");
4941     }
4942 
4943     /**
4944      * @hide
4945      */
getAutofillClient()4946     public AutofillClient getAutofillClient() {
4947         return null;
4948     }
4949 
4950     /**
4951      * @hide
4952      */
setAutofillClient(@uppressWarnings"unused") AutofillClient client)4953     public void setAutofillClient(@SuppressWarnings("unused") AutofillClient client) {
4954     }
4955 
4956     /**
4957      * @hide
4958      */
isAutofillCompatibilityEnabled()4959     public boolean isAutofillCompatibilityEnabled() {
4960         return false;
4961     }
4962 
4963     /**
4964      * @hide
4965      */
4966     @TestApi
setAutofillCompatibilityEnabled( @uppressWarnings"unused") boolean autofillCompatEnabled)4967     public void setAutofillCompatibilityEnabled(
4968             @SuppressWarnings("unused") boolean autofillCompatEnabled) {
4969     }
4970 
4971     /**
4972      * Throws an exception if the Context is using system resources,
4973      * which are non-runtime-overlay-themable and may show inconsistent UI.
4974      * @hide
4975      */
assertRuntimeOverlayThemable()4976     public void assertRuntimeOverlayThemable() {
4977         // Resources.getSystem() is a singleton and the only Resources not managed by
4978         // ResourcesManager; therefore Resources.getSystem() is not themable.
4979         if (getResources() == Resources.getSystem()) {
4980             throw new IllegalArgumentException("Non-UI context used to display UI; "
4981                     + "get a UI context from ActivityThread#getSystemUiContext()");
4982         }
4983     }
4984 }
4985