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