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