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