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