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