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