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