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