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