OSDN Git Service

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