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