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