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