AppOpsManager.java revision 65a4f251c7e14307f46911e376db49c8c7a1a8bb
1/*
2 * Copyright (C) 2012 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.app;
18
19import android.Manifest;
20import android.annotation.NonNull;
21import android.annotation.RequiresPermission;
22import android.annotation.SystemApi;
23import android.annotation.SystemService;
24import android.annotation.TestApi;
25import android.app.usage.UsageStatsManager;
26import android.content.Context;
27import android.media.AudioAttributes.AttributeUsage;
28import android.os.Binder;
29import android.os.IBinder;
30import android.os.Parcel;
31import android.os.Parcelable;
32import android.os.Process;
33import android.os.RemoteException;
34import android.os.UserManager;
35import android.util.ArrayMap;
36
37import com.android.internal.app.IAppOpsActiveCallback;
38import com.android.internal.app.IAppOpsCallback;
39import com.android.internal.app.IAppOpsService;
40import com.android.internal.util.Preconditions;
41
42import java.util.ArrayList;
43import java.util.Arrays;
44import java.util.HashMap;
45import java.util.List;
46
47/**
48 * API for interacting with "application operation" tracking.
49 *
50 * <p>This API is not generally intended for third party application developers; most
51 * features are only available to system applications.
52 */
53@SystemService(Context.APP_OPS_SERVICE)
54public class AppOpsManager {
55    /**
56     * <p>App ops allows callers to:</p>
57     *
58     * <ul>
59     * <li> Note when operations are happening, and find out if they are allowed for the current
60     * caller.</li>
61     * <li> Disallow specific apps from doing specific operations.</li>
62     * <li> Collect all of the current information about operations that have been executed or
63     * are not being allowed.</li>
64     * <li> Monitor for changes in whether an operation is allowed.</li>
65     * </ul>
66     *
67     * <p>Each operation is identified by a single integer; these integers are a fixed set of
68     * operations, enumerated by the OP_* constants.
69     *
70     * <p></p>When checking operations, the result is a "mode" integer indicating the current
71     * setting for the operation under that caller: MODE_ALLOWED, MODE_IGNORED (don't execute
72     * the operation but fake its behavior enough so that the caller doesn't crash),
73     * MODE_ERRORED (throw a SecurityException back to the caller; the normal operation calls
74     * will do this for you).
75     */
76
77    final Context mContext;
78    final IAppOpsService mService;
79    final ArrayMap<OnOpChangedListener, IAppOpsCallback> mModeWatchers = new ArrayMap<>();
80    final ArrayMap<OnOpActiveChangedListener, IAppOpsActiveCallback> mActiveWatchers =
81            new ArrayMap<>();
82
83    static IBinder sToken;
84
85    /**
86     * Result from {@link #checkOp}, {@link #noteOp}, {@link #startOp}: the given caller is
87     * allowed to perform the given operation.
88     */
89    public static final int MODE_ALLOWED = 0;
90
91    /**
92     * Result from {@link #checkOp}, {@link #noteOp}, {@link #startOp}: the given caller is
93     * not allowed to perform the given operation, and this attempt should
94     * <em>silently fail</em> (it should not cause the app to crash).
95     */
96    public static final int MODE_IGNORED = 1;
97
98    /**
99     * Result from {@link #checkOpNoThrow}, {@link #noteOpNoThrow}, {@link #startOpNoThrow}: the
100     * given caller is not allowed to perform the given operation, and this attempt should
101     * cause it to have a fatal error, typically a {@link SecurityException}.
102     */
103    public static final int MODE_ERRORED = 2;
104
105    /**
106     * Result from {@link #checkOp}, {@link #noteOp}, {@link #startOp}: the given caller should
107     * use its default security check.  This mode is not normally used; it should only be used
108     * with appop permissions, and callers must explicitly check for it and deal with it.
109     */
110    public static final int MODE_DEFAULT = 3;
111
112    /**
113     * Special mode that means "allow only when app is in foreground."  This is <b>not</b>
114     * returned from {@link #checkOp}, {@link #noteOp}, {@link #startOp}; rather, when this
115     * mode is set, these functions will return {@link #MODE_ALLOWED} when the app being
116     * checked is currently in the foreground, otherwise {@link #MODE_IGNORED}.
117     * @hide
118     */
119    public static final int MODE_FOREGROUND = 4;
120
121    /**
122     * Flag for {@link #startWatchingMode(String, String, int, OnOpChangedListener)}:
123     * Also get reports if the foreground state of an op's uid changes.  This only works
124     * when watching a particular op, not when watching a package.
125     * @hide
126     */
127    public static final int WATCH_FOREGROUND_CHANGES = 1 << 0;
128
129    /**
130     * @hide
131     */
132    public static final String[] MODE_NAMES = new String[] {
133            "allow",        // MODE_ALLOWED
134            "ignore",       // MODE_IGNORED
135            "deny",         // MODE_ERRORED
136            "default",      // MODE_DEFAULT
137            "foreground",   // MODE_FOREGROUND
138    };
139
140    /**
141     * Metrics about an op when its uid is persistent.
142     * @hide
143     */
144    public static final int UID_STATE_PERSISTENT = 0;
145
146    /**
147     * Metrics about an op when its uid is at the top.
148     * @hide
149     */
150    public static final int UID_STATE_TOP = 1;
151
152    /**
153     * Metrics about an op when its uid is running a foreground service.
154     * @hide
155     */
156    public static final int UID_STATE_FOREGROUND_SERVICE = 2;
157
158    /**
159     * Metrics about an op when its uid is in the foreground for any other reasons.
160     * @hide
161     */
162    public static final int UID_STATE_FOREGROUND = 3;
163
164    /**
165     * Metrics about an op when its uid is in the background for any reason.
166     * @hide
167     */
168    public static final int UID_STATE_BACKGROUND = 4;
169
170    /**
171     * Metrics about an op when its uid is cached.
172     * @hide
173     */
174    public static final int UID_STATE_CACHED = 5;
175
176    /**
177     * Number of uid states we track.
178     * @hide
179     */
180    public static final int _NUM_UID_STATE = 6;
181
182    // when adding one of these:
183    //  - increment _NUM_OP
184    //  - define an OPSTR_* constant (marked as @SystemApi)
185    //  - add rows to sOpToSwitch, sOpToString, sOpNames, sOpToPerms, sOpDefault
186    //  - add descriptive strings to Settings/res/values/arrays.xml
187    //  - add the op to the appropriate template in AppOpsState.OpsTemplate (settings app)
188
189    /** @hide No operation specified. */
190    public static final int OP_NONE = -1;
191    /** @hide Access to coarse location information. */
192    public static final int OP_COARSE_LOCATION = 0;
193    /** @hide Access to fine location information. */
194    public static final int OP_FINE_LOCATION = 1;
195    /** @hide Causing GPS to run. */
196    public static final int OP_GPS = 2;
197    /** @hide */
198    public static final int OP_VIBRATE = 3;
199    /** @hide */
200    public static final int OP_READ_CONTACTS = 4;
201    /** @hide */
202    public static final int OP_WRITE_CONTACTS = 5;
203    /** @hide */
204    public static final int OP_READ_CALL_LOG = 6;
205    /** @hide */
206    public static final int OP_WRITE_CALL_LOG = 7;
207    /** @hide */
208    public static final int OP_READ_CALENDAR = 8;
209    /** @hide */
210    public static final int OP_WRITE_CALENDAR = 9;
211    /** @hide */
212    public static final int OP_WIFI_SCAN = 10;
213    /** @hide */
214    public static final int OP_POST_NOTIFICATION = 11;
215    /** @hide */
216    public static final int OP_NEIGHBORING_CELLS = 12;
217    /** @hide */
218    public static final int OP_CALL_PHONE = 13;
219    /** @hide */
220    public static final int OP_READ_SMS = 14;
221    /** @hide */
222    public static final int OP_WRITE_SMS = 15;
223    /** @hide */
224    public static final int OP_RECEIVE_SMS = 16;
225    /** @hide */
226    public static final int OP_RECEIVE_EMERGECY_SMS = 17;
227    /** @hide */
228    public static final int OP_RECEIVE_MMS = 18;
229    /** @hide */
230    public static final int OP_RECEIVE_WAP_PUSH = 19;
231    /** @hide */
232    public static final int OP_SEND_SMS = 20;
233    /** @hide */
234    public static final int OP_READ_ICC_SMS = 21;
235    /** @hide */
236    public static final int OP_WRITE_ICC_SMS = 22;
237    /** @hide */
238    public static final int OP_WRITE_SETTINGS = 23;
239    /** @hide Required to draw on top of other apps. */
240    @TestApi
241    public static final int OP_SYSTEM_ALERT_WINDOW = 24;
242    /** @hide */
243    public static final int OP_ACCESS_NOTIFICATIONS = 25;
244    /** @hide */
245    public static final int OP_CAMERA = 26;
246    /** @hide */
247    @TestApi
248    public static final int OP_RECORD_AUDIO = 27;
249    /** @hide */
250    public static final int OP_PLAY_AUDIO = 28;
251    /** @hide */
252    public static final int OP_READ_CLIPBOARD = 29;
253    /** @hide */
254    public static final int OP_WRITE_CLIPBOARD = 30;
255    /** @hide */
256    public static final int OP_TAKE_MEDIA_BUTTONS = 31;
257    /** @hide */
258    public static final int OP_TAKE_AUDIO_FOCUS = 32;
259    /** @hide */
260    public static final int OP_AUDIO_MASTER_VOLUME = 33;
261    /** @hide */
262    public static final int OP_AUDIO_VOICE_VOLUME = 34;
263    /** @hide */
264    public static final int OP_AUDIO_RING_VOLUME = 35;
265    /** @hide */
266    public static final int OP_AUDIO_MEDIA_VOLUME = 36;
267    /** @hide */
268    public static final int OP_AUDIO_ALARM_VOLUME = 37;
269    /** @hide */
270    public static final int OP_AUDIO_NOTIFICATION_VOLUME = 38;
271    /** @hide */
272    public static final int OP_AUDIO_BLUETOOTH_VOLUME = 39;
273    /** @hide */
274    public static final int OP_WAKE_LOCK = 40;
275    /** @hide Continually monitoring location data. */
276    public static final int OP_MONITOR_LOCATION = 41;
277    /** @hide Continually monitoring location data with a relatively high power request. */
278    public static final int OP_MONITOR_HIGH_POWER_LOCATION = 42;
279    /** @hide Retrieve current usage stats via {@link UsageStatsManager}. */
280    public static final int OP_GET_USAGE_STATS = 43;
281    /** @hide */
282    public static final int OP_MUTE_MICROPHONE = 44;
283    /** @hide */
284    public static final int OP_TOAST_WINDOW = 45;
285    /** @hide Capture the device's display contents and/or audio */
286    public static final int OP_PROJECT_MEDIA = 46;
287    /** @hide Activate a VPN connection without user intervention. */
288    public static final int OP_ACTIVATE_VPN = 47;
289    /** @hide Access the WallpaperManagerAPI to write wallpapers. */
290    public static final int OP_WRITE_WALLPAPER = 48;
291    /** @hide Received the assist structure from an app. */
292    public static final int OP_ASSIST_STRUCTURE = 49;
293    /** @hide Received a screenshot from assist. */
294    public static final int OP_ASSIST_SCREENSHOT = 50;
295    /** @hide Read the phone state. */
296    public static final int OP_READ_PHONE_STATE = 51;
297    /** @hide Add voicemail messages to the voicemail content provider. */
298    public static final int OP_ADD_VOICEMAIL = 52;
299    /** @hide Access APIs for SIP calling over VOIP or WiFi. */
300    public static final int OP_USE_SIP = 53;
301    /** @hide Intercept outgoing calls. */
302    public static final int OP_PROCESS_OUTGOING_CALLS = 54;
303    /** @hide User the fingerprint API. */
304    public static final int OP_USE_FINGERPRINT = 55;
305    /** @hide Access to body sensors such as heart rate, etc. */
306    public static final int OP_BODY_SENSORS = 56;
307    /** @hide Read previously received cell broadcast messages. */
308    public static final int OP_READ_CELL_BROADCASTS = 57;
309    /** @hide Inject mock location into the system. */
310    public static final int OP_MOCK_LOCATION = 58;
311    /** @hide Read external storage. */
312    public static final int OP_READ_EXTERNAL_STORAGE = 59;
313    /** @hide Write external storage. */
314    public static final int OP_WRITE_EXTERNAL_STORAGE = 60;
315    /** @hide Turned on the screen. */
316    public static final int OP_TURN_SCREEN_ON = 61;
317    /** @hide Get device accounts. */
318    public static final int OP_GET_ACCOUNTS = 62;
319    /** @hide Control whether an application is allowed to run in the background. */
320    public static final int OP_RUN_IN_BACKGROUND = 63;
321    /** @hide */
322    public static final int OP_AUDIO_ACCESSIBILITY_VOLUME = 64;
323    /** @hide Read the phone number. */
324    public static final int OP_READ_PHONE_NUMBERS = 65;
325    /** @hide Request package installs through package installer */
326    public static final int OP_REQUEST_INSTALL_PACKAGES = 66;
327    /** @hide Enter picture-in-picture. */
328    public static final int OP_PICTURE_IN_PICTURE = 67;
329    /** @hide Instant app start foreground service. */
330    public static final int OP_INSTANT_APP_START_FOREGROUND = 68;
331    /** @hide Answer incoming phone calls */
332    public static final int OP_ANSWER_PHONE_CALLS = 69;
333    /** @hide Run jobs when in background */
334    public static final int OP_RUN_ANY_IN_BACKGROUND = 70;
335    /** @hide Change Wi-Fi connectivity state */
336    public static final int OP_CHANGE_WIFI_STATE = 71;
337    /** @hide Request package deletion through package installer */
338    public static final int OP_REQUEST_DELETE_PACKAGES = 72;
339    /** @hide Bind an accessibility service. */
340    public static final int OP_BIND_ACCESSIBILITY_SERVICE = 73;
341    /** @hide Continue handover of a call from another app */
342    public static final int OP_ACCEPT_HANDOVER = 74;
343    /** @hide Create and Manage IPsec Tunnels */
344    public static final int OP_MANAGE_IPSEC_TUNNELS = 75;
345    /** @hide Any app start foreground service. */
346    public static final int OP_START_FOREGROUND = 76;
347    /** @hide */
348    public static final int OP_BLUETOOTH_SCAN = 77;
349    /** @hide */
350    public static final int _NUM_OP = 78;
351
352    /** Access to coarse location information. */
353    public static final String OPSTR_COARSE_LOCATION = "android:coarse_location";
354    /** Access to fine location information. */
355    public static final String OPSTR_FINE_LOCATION =
356            "android:fine_location";
357    /** Continually monitoring location data. */
358    public static final String OPSTR_MONITOR_LOCATION
359            = "android:monitor_location";
360    /** Continually monitoring location data with a relatively high power request. */
361    public static final String OPSTR_MONITOR_HIGH_POWER_LOCATION
362            = "android:monitor_location_high_power";
363    /** Access to {@link android.app.usage.UsageStatsManager}. */
364    public static final String OPSTR_GET_USAGE_STATS
365            = "android:get_usage_stats";
366    /** Activate a VPN connection without user intervention. @hide */
367    @SystemApi @TestApi
368    public static final String OPSTR_ACTIVATE_VPN
369            = "android:activate_vpn";
370    /** Allows an application to read the user's contacts data. */
371    public static final String OPSTR_READ_CONTACTS
372            = "android:read_contacts";
373    /** Allows an application to write to the user's contacts data. */
374    public static final String OPSTR_WRITE_CONTACTS
375            = "android:write_contacts";
376    /** Allows an application to read the user's call log. */
377    public static final String OPSTR_READ_CALL_LOG
378            = "android:read_call_log";
379    /** Allows an application to write to the user's call log. */
380    public static final String OPSTR_WRITE_CALL_LOG
381            = "android:write_call_log";
382    /** Allows an application to read the user's calendar data. */
383    public static final String OPSTR_READ_CALENDAR
384            = "android:read_calendar";
385    /** Allows an application to write to the user's calendar data. */
386    public static final String OPSTR_WRITE_CALENDAR
387            = "android:write_calendar";
388    /** Allows an application to initiate a phone call. */
389    public static final String OPSTR_CALL_PHONE
390            = "android:call_phone";
391    /** Allows an application to read SMS messages. */
392    public static final String OPSTR_READ_SMS
393            = "android:read_sms";
394    /** Allows an application to receive SMS messages. */
395    public static final String OPSTR_RECEIVE_SMS
396            = "android:receive_sms";
397    /** Allows an application to receive MMS messages. */
398    public static final String OPSTR_RECEIVE_MMS
399            = "android:receive_mms";
400    /** Allows an application to receive WAP push messages. */
401    public static final String OPSTR_RECEIVE_WAP_PUSH
402            = "android:receive_wap_push";
403    /** Allows an application to send SMS messages. */
404    public static final String OPSTR_SEND_SMS
405            = "android:send_sms";
406    /** Required to be able to access the camera device. */
407    public static final String OPSTR_CAMERA
408            = "android:camera";
409    /** Required to be able to access the microphone device. */
410    public static final String OPSTR_RECORD_AUDIO
411            = "android:record_audio";
412    /** Required to access phone state related information. */
413    public static final String OPSTR_READ_PHONE_STATE
414            = "android:read_phone_state";
415    /** Required to access phone state related information. */
416    public static final String OPSTR_ADD_VOICEMAIL
417            = "android:add_voicemail";
418    /** Access APIs for SIP calling over VOIP or WiFi */
419    public static final String OPSTR_USE_SIP
420            = "android:use_sip";
421    /** Access APIs for diverting outgoing calls */
422    public static final String OPSTR_PROCESS_OUTGOING_CALLS
423            = "android:process_outgoing_calls";
424    /** Use the fingerprint API. */
425    public static final String OPSTR_USE_FINGERPRINT
426            = "android:use_fingerprint";
427    /** Access to body sensors such as heart rate, etc. */
428    public static final String OPSTR_BODY_SENSORS
429            = "android:body_sensors";
430    /** Read previously received cell broadcast messages. */
431    public static final String OPSTR_READ_CELL_BROADCASTS
432            = "android:read_cell_broadcasts";
433    /** Inject mock location into the system. */
434    public static final String OPSTR_MOCK_LOCATION
435            = "android:mock_location";
436    /** Read external storage. */
437    public static final String OPSTR_READ_EXTERNAL_STORAGE
438            = "android:read_external_storage";
439    /** Write external storage. */
440    public static final String OPSTR_WRITE_EXTERNAL_STORAGE
441            = "android:write_external_storage";
442    /** Required to draw on top of other apps. */
443    public static final String OPSTR_SYSTEM_ALERT_WINDOW
444            = "android:system_alert_window";
445    /** Required to write/modify/update system settingss. */
446    public static final String OPSTR_WRITE_SETTINGS
447            = "android:write_settings";
448    /** @hide Get device accounts. */
449    @SystemApi @TestApi
450    public static final String OPSTR_GET_ACCOUNTS
451            = "android:get_accounts";
452    public static final String OPSTR_READ_PHONE_NUMBERS
453            = "android:read_phone_numbers";
454    /** Access to picture-in-picture. */
455    public static final String OPSTR_PICTURE_IN_PICTURE
456            = "android:picture_in_picture";
457    /** @hide */
458    @SystemApi @TestApi
459    public static final String OPSTR_INSTANT_APP_START_FOREGROUND
460            = "android:instant_app_start_foreground";
461    /** Answer incoming phone calls */
462    public static final String OPSTR_ANSWER_PHONE_CALLS
463            = "android:answer_phone_calls";
464    /**
465     * Accept call handover
466     * @hide
467     */
468    @SystemApi @TestApi
469    public static final String OPSTR_ACCEPT_HANDOVER
470            = "android:accept_handover";
471    /** @hide */
472    @SystemApi @TestApi
473    public static final String OPSTR_GPS = "android:gps";
474    /** @hide */
475    @SystemApi @TestApi
476    public static final String OPSTR_VIBRATE = "android:vibrate";
477    /** @hide */
478    @SystemApi @TestApi
479    public static final String OPSTR_WIFI_SCAN = "android:wifi_scan";
480    /** @hide */
481    @SystemApi @TestApi
482    public static final String OPSTR_POST_NOTIFICATION = "android:post_notification";
483    /** @hide */
484    @SystemApi @TestApi
485    public static final String OPSTR_NEIGHBORING_CELLS = "android:neighboring_cells";
486    /** @hide */
487    @SystemApi @TestApi
488    public static final String OPSTR_WRITE_SMS = "android:write_sms";
489    /** @hide */
490    @SystemApi @TestApi
491    public static final String OPSTR_RECEIVE_EMERGENCY_BROADCAST =
492            "android:receive_emergency_broadcast";
493    /** @hide */
494    @SystemApi @TestApi
495    public static final String OPSTR_READ_ICC_SMS = "android:read_icc_sms";
496    /** @hide */
497    @SystemApi @TestApi
498    public static final String OPSTR_WRITE_ICC_SMS = "android:write_icc_sms";
499    /** @hide */
500    @SystemApi @TestApi
501    public static final String OPSTR_ACCESS_NOTIFICATIONS = "android:access_notifications";
502    /** @hide */
503    @SystemApi @TestApi
504    public static final String OPSTR_PLAY_AUDIO = "android:play_audio";
505    /** @hide */
506    @SystemApi @TestApi
507    public static final String OPSTR_READ_CLIPBOARD = "android:read_clipboard";
508    /** @hide */
509    @SystemApi @TestApi
510    public static final String OPSTR_WRITE_CLIPBOARD = "android:write_clipboard";
511    /** @hide */
512    @SystemApi @TestApi
513    public static final String OPSTR_TAKE_MEDIA_BUTTONS = "android:take_media_buttons";
514    /** @hide */
515    @SystemApi @TestApi
516    public static final String OPSTR_TAKE_AUDIO_FOCUS = "android:take_audio_focus";
517    /** @hide */
518    @SystemApi @TestApi
519    public static final String OPSTR_AUDIO_MASTER_VOLUME = "android:audio_master_volume";
520    /** @hide */
521    @SystemApi @TestApi
522    public static final String OPSTR_AUDIO_VOICE_VOLUME = "android:audio_voice_volume";
523    /** @hide */
524    @SystemApi @TestApi
525    public static final String OPSTR_AUDIO_RING_VOLUME = "android:audio_ring_volume";
526    /** @hide */
527    @SystemApi @TestApi
528    public static final String OPSTR_AUDIO_MEDIA_VOLUME = "android:audio_media_volume";
529    /** @hide */
530    @SystemApi @TestApi
531    public static final String OPSTR_AUDIO_ALARM_VOLUME = "android:audio_alarm_volume";
532    /** @hide */
533    @SystemApi @TestApi
534    public static final String OPSTR_AUDIO_NOTIFICATION_VOLUME =
535            "android:audio_notification_volume";
536    /** @hide */
537    @SystemApi @TestApi
538    public static final String OPSTR_AUDIO_BLUETOOTH_VOLUME = "android:audio_bluetooth_volume";
539    /** @hide */
540    @SystemApi @TestApi
541    public static final String OPSTR_WAKE_LOCK = "android:wake_lock";
542    /** @hide */
543    @SystemApi @TestApi
544    public static final String OPSTR_MUTE_MICROPHONE = "android:mute_microphone";
545    /** @hide */
546    @SystemApi @TestApi
547    public static final String OPSTR_TOAST_WINDOW = "android:toast_window";
548    /** @hide */
549    @SystemApi @TestApi
550    public static final String OPSTR_PROJECT_MEDIA = "android:project_media";
551    /** @hide */
552    @SystemApi @TestApi
553    public static final String OPSTR_WRITE_WALLPAPER = "android:write_wallpaper";
554    /** @hide */
555    @SystemApi @TestApi
556    public static final String OPSTR_ASSIST_STRUCTURE = "android:assist_structure";
557    /** @hide */
558    @SystemApi @TestApi
559    public static final String OPSTR_ASSIST_SCREENSHOT = "android:assist_screenshot";
560    /** @hide */
561    @SystemApi @TestApi
562    public static final String OPSTR_TURN_SCREEN_ON = "android:turn_screen_on";
563    /** @hide */
564    @SystemApi @TestApi
565    public static final String OPSTR_RUN_IN_BACKGROUND = "android:run_in_background";
566    /** @hide */
567    @SystemApi @TestApi
568    public static final String OPSTR_AUDIO_ACCESSIBILITY_VOLUME =
569            "android:audio_accessibility_volume";
570    /** @hide */
571    @SystemApi @TestApi
572    public static final String OPSTR_REQUEST_INSTALL_PACKAGES = "android:request_install_packages";
573    /** @hide */
574    @SystemApi @TestApi
575    public static final String OPSTR_RUN_ANY_IN_BACKGROUND = "android:run_any_in_background";
576    /** @hide */
577    @SystemApi @TestApi
578    public static final String OPSTR_CHANGE_WIFI_STATE = "android:change_wifi_state";
579    /** @hide */
580    @SystemApi @TestApi
581    public static final String OPSTR_REQUEST_DELETE_PACKAGES = "android:request_delete_packages";
582    /** @hide */
583    @SystemApi @TestApi
584    public static final String OPSTR_BIND_ACCESSIBILITY_SERVICE =
585            "android:bind_accessibility_service";
586    /** @hide */
587    @SystemApi @TestApi
588    public static final String OPSTR_MANAGE_IPSEC_TUNNELS = "android:manage_ipsec_tunnels";
589    /** @hide */
590    @SystemApi @TestApi
591    public static final String OPSTR_START_FOREGROUND = "android:start_foreground";
592    /** @hide */
593    public static final String OPSTR_BLUETOOTH_SCAN = "android:bluetooth_scan";
594
595    // Warning: If an permission is added here it also has to be added to
596    // com.android.packageinstaller.permission.utils.EventLogger
597    private static final int[] RUNTIME_AND_APPOP_PERMISSIONS_OPS = {
598            // RUNTIME PERMISSIONS
599            // Contacts
600            OP_READ_CONTACTS,
601            OP_WRITE_CONTACTS,
602            OP_GET_ACCOUNTS,
603            // Calendar
604            OP_READ_CALENDAR,
605            OP_WRITE_CALENDAR,
606            // SMS
607            OP_SEND_SMS,
608            OP_RECEIVE_SMS,
609            OP_READ_SMS,
610            OP_RECEIVE_WAP_PUSH,
611            OP_RECEIVE_MMS,
612            OP_READ_CELL_BROADCASTS,
613            // Storage
614            OP_READ_EXTERNAL_STORAGE,
615            OP_WRITE_EXTERNAL_STORAGE,
616            // Location
617            OP_COARSE_LOCATION,
618            OP_FINE_LOCATION,
619            // Phone
620            OP_READ_PHONE_STATE,
621            OP_READ_PHONE_NUMBERS,
622            OP_CALL_PHONE,
623            OP_READ_CALL_LOG,
624            OP_WRITE_CALL_LOG,
625            OP_ADD_VOICEMAIL,
626            OP_USE_SIP,
627            OP_PROCESS_OUTGOING_CALLS,
628            OP_ANSWER_PHONE_CALLS,
629            OP_ACCEPT_HANDOVER,
630            // Microphone
631            OP_RECORD_AUDIO,
632            // Camera
633            OP_CAMERA,
634            // Body sensors
635            OP_BODY_SENSORS,
636
637            // APPOP PERMISSIONS
638            OP_ACCESS_NOTIFICATIONS,
639            OP_SYSTEM_ALERT_WINDOW,
640            OP_WRITE_SETTINGS,
641            OP_REQUEST_INSTALL_PACKAGES,
642            OP_START_FOREGROUND,
643    };
644
645    /**
646     * This maps each operation to the operation that serves as the
647     * switch to determine whether it is allowed.  Generally this is
648     * a 1:1 mapping, but for some things (like location) that have
649     * multiple low-level operations being tracked that should be
650     * presented to the user as one switch then this can be used to
651     * make them all controlled by the same single operation.
652     */
653    private static int[] sOpToSwitch = new int[] {
654            OP_COARSE_LOCATION,                 // COARSE_LOCATION
655            OP_COARSE_LOCATION,                 // FINE_LOCATION
656            OP_COARSE_LOCATION,                 // GPS
657            OP_VIBRATE,                         // VIBRATE
658            OP_READ_CONTACTS,                   // READ_CONTACTS
659            OP_WRITE_CONTACTS,                  // WRITE_CONTACTS
660            OP_READ_CALL_LOG,                   // READ_CALL_LOG
661            OP_WRITE_CALL_LOG,                  // WRITE_CALL_LOG
662            OP_READ_CALENDAR,                   // READ_CALENDAR
663            OP_WRITE_CALENDAR,                  // WRITE_CALENDAR
664            OP_COARSE_LOCATION,                 // WIFI_SCAN
665            OP_POST_NOTIFICATION,               // POST_NOTIFICATION
666            OP_COARSE_LOCATION,                 // NEIGHBORING_CELLS
667            OP_CALL_PHONE,                      // CALL_PHONE
668            OP_READ_SMS,                        // READ_SMS
669            OP_WRITE_SMS,                       // WRITE_SMS
670            OP_RECEIVE_SMS,                     // RECEIVE_SMS
671            OP_RECEIVE_SMS,                     // RECEIVE_EMERGECY_SMS
672            OP_RECEIVE_MMS,                     // RECEIVE_MMS
673            OP_RECEIVE_WAP_PUSH,                // RECEIVE_WAP_PUSH
674            OP_SEND_SMS,                        // SEND_SMS
675            OP_READ_SMS,                        // READ_ICC_SMS
676            OP_WRITE_SMS,                       // WRITE_ICC_SMS
677            OP_WRITE_SETTINGS,                  // WRITE_SETTINGS
678            OP_SYSTEM_ALERT_WINDOW,             // SYSTEM_ALERT_WINDOW
679            OP_ACCESS_NOTIFICATIONS,            // ACCESS_NOTIFICATIONS
680            OP_CAMERA,                          // CAMERA
681            OP_RECORD_AUDIO,                    // RECORD_AUDIO
682            OP_PLAY_AUDIO,                      // PLAY_AUDIO
683            OP_READ_CLIPBOARD,                  // READ_CLIPBOARD
684            OP_WRITE_CLIPBOARD,                 // WRITE_CLIPBOARD
685            OP_TAKE_MEDIA_BUTTONS,              // TAKE_MEDIA_BUTTONS
686            OP_TAKE_AUDIO_FOCUS,                // TAKE_AUDIO_FOCUS
687            OP_AUDIO_MASTER_VOLUME,             // AUDIO_MASTER_VOLUME
688            OP_AUDIO_VOICE_VOLUME,              // AUDIO_VOICE_VOLUME
689            OP_AUDIO_RING_VOLUME,               // AUDIO_RING_VOLUME
690            OP_AUDIO_MEDIA_VOLUME,              // AUDIO_MEDIA_VOLUME
691            OP_AUDIO_ALARM_VOLUME,              // AUDIO_ALARM_VOLUME
692            OP_AUDIO_NOTIFICATION_VOLUME,       // AUDIO_NOTIFICATION_VOLUME
693            OP_AUDIO_BLUETOOTH_VOLUME,          // AUDIO_BLUETOOTH_VOLUME
694            OP_WAKE_LOCK,                       // WAKE_LOCK
695            OP_COARSE_LOCATION,                 // MONITOR_LOCATION
696            OP_COARSE_LOCATION,                 // MONITOR_HIGH_POWER_LOCATION
697            OP_GET_USAGE_STATS,                 // GET_USAGE_STATS
698            OP_MUTE_MICROPHONE,                 // MUTE_MICROPHONE
699            OP_TOAST_WINDOW,                    // TOAST_WINDOW
700            OP_PROJECT_MEDIA,                   // PROJECT_MEDIA
701            OP_ACTIVATE_VPN,                    // ACTIVATE_VPN
702            OP_WRITE_WALLPAPER,                 // WRITE_WALLPAPER
703            OP_ASSIST_STRUCTURE,                // ASSIST_STRUCTURE
704            OP_ASSIST_SCREENSHOT,               // ASSIST_SCREENSHOT
705            OP_READ_PHONE_STATE,                // READ_PHONE_STATE
706            OP_ADD_VOICEMAIL,                   // ADD_VOICEMAIL
707            OP_USE_SIP,                         // USE_SIP
708            OP_PROCESS_OUTGOING_CALLS,          // PROCESS_OUTGOING_CALLS
709            OP_USE_FINGERPRINT,                 // USE_FINGERPRINT
710            OP_BODY_SENSORS,                    // BODY_SENSORS
711            OP_READ_CELL_BROADCASTS,            // READ_CELL_BROADCASTS
712            OP_MOCK_LOCATION,                   // MOCK_LOCATION
713            OP_READ_EXTERNAL_STORAGE,           // READ_EXTERNAL_STORAGE
714            OP_WRITE_EXTERNAL_STORAGE,          // WRITE_EXTERNAL_STORAGE
715            OP_TURN_SCREEN_ON,                  // TURN_SCREEN_ON
716            OP_GET_ACCOUNTS,                    // GET_ACCOUNTS
717            OP_RUN_IN_BACKGROUND,               // RUN_IN_BACKGROUND
718            OP_AUDIO_ACCESSIBILITY_VOLUME,      // AUDIO_ACCESSIBILITY_VOLUME
719            OP_READ_PHONE_NUMBERS,              // READ_PHONE_NUMBERS
720            OP_REQUEST_INSTALL_PACKAGES,        // REQUEST_INSTALL_PACKAGES
721            OP_PICTURE_IN_PICTURE,              // ENTER_PICTURE_IN_PICTURE_ON_HIDE
722            OP_INSTANT_APP_START_FOREGROUND,    // INSTANT_APP_START_FOREGROUND
723            OP_ANSWER_PHONE_CALLS,              // ANSWER_PHONE_CALLS
724            OP_RUN_ANY_IN_BACKGROUND,           // OP_RUN_ANY_IN_BACKGROUND
725            OP_CHANGE_WIFI_STATE,               // OP_CHANGE_WIFI_STATE
726            OP_REQUEST_DELETE_PACKAGES,         // OP_REQUEST_DELETE_PACKAGES
727            OP_BIND_ACCESSIBILITY_SERVICE,      // OP_BIND_ACCESSIBILITY_SERVICE
728            OP_ACCEPT_HANDOVER,                 // ACCEPT_HANDOVER
729            OP_MANAGE_IPSEC_TUNNELS,            // MANAGE_IPSEC_HANDOVERS
730            OP_START_FOREGROUND,                // START_FOREGROUND
731            OP_COARSE_LOCATION,                 // BLUETOOTH_SCAN
732    };
733
734    /**
735     * This maps each operation to the public string constant for it.
736     */
737    private static String[] sOpToString = new String[]{
738            OPSTR_COARSE_LOCATION,
739            OPSTR_FINE_LOCATION,
740            OPSTR_GPS,
741            OPSTR_VIBRATE,
742            OPSTR_READ_CONTACTS,
743            OPSTR_WRITE_CONTACTS,
744            OPSTR_READ_CALL_LOG,
745            OPSTR_WRITE_CALL_LOG,
746            OPSTR_READ_CALENDAR,
747            OPSTR_WRITE_CALENDAR,
748            OPSTR_WIFI_SCAN,
749            OPSTR_POST_NOTIFICATION,
750            OPSTR_NEIGHBORING_CELLS,
751            OPSTR_CALL_PHONE,
752            OPSTR_READ_SMS,
753            OPSTR_WRITE_SMS,
754            OPSTR_RECEIVE_SMS,
755            OPSTR_RECEIVE_EMERGENCY_BROADCAST,
756            OPSTR_RECEIVE_MMS,
757            OPSTR_RECEIVE_WAP_PUSH,
758            OPSTR_SEND_SMS,
759            OPSTR_READ_ICC_SMS,
760            OPSTR_WRITE_ICC_SMS,
761            OPSTR_WRITE_SETTINGS,
762            OPSTR_SYSTEM_ALERT_WINDOW,
763            OPSTR_ACCESS_NOTIFICATIONS,
764            OPSTR_CAMERA,
765            OPSTR_RECORD_AUDIO,
766            OPSTR_PLAY_AUDIO,
767            OPSTR_READ_CLIPBOARD,
768            OPSTR_WRITE_CLIPBOARD,
769            OPSTR_TAKE_MEDIA_BUTTONS,
770            OPSTR_TAKE_AUDIO_FOCUS,
771            OPSTR_AUDIO_MASTER_VOLUME,
772            OPSTR_AUDIO_VOICE_VOLUME,
773            OPSTR_AUDIO_RING_VOLUME,
774            OPSTR_AUDIO_MEDIA_VOLUME,
775            OPSTR_AUDIO_ALARM_VOLUME,
776            OPSTR_AUDIO_NOTIFICATION_VOLUME,
777            OPSTR_AUDIO_BLUETOOTH_VOLUME,
778            OPSTR_WAKE_LOCK,
779            OPSTR_MONITOR_LOCATION,
780            OPSTR_MONITOR_HIGH_POWER_LOCATION,
781            OPSTR_GET_USAGE_STATS,
782            OPSTR_MUTE_MICROPHONE,
783            OPSTR_TOAST_WINDOW,
784            OPSTR_PROJECT_MEDIA,
785            OPSTR_ACTIVATE_VPN,
786            OPSTR_WRITE_WALLPAPER,
787            OPSTR_ASSIST_STRUCTURE,
788            OPSTR_ASSIST_SCREENSHOT,
789            OPSTR_READ_PHONE_STATE,
790            OPSTR_ADD_VOICEMAIL,
791            OPSTR_USE_SIP,
792            OPSTR_PROCESS_OUTGOING_CALLS,
793            OPSTR_USE_FINGERPRINT,
794            OPSTR_BODY_SENSORS,
795            OPSTR_READ_CELL_BROADCASTS,
796            OPSTR_MOCK_LOCATION,
797            OPSTR_READ_EXTERNAL_STORAGE,
798            OPSTR_WRITE_EXTERNAL_STORAGE,
799            OPSTR_TURN_SCREEN_ON,
800            OPSTR_GET_ACCOUNTS,
801            OPSTR_RUN_IN_BACKGROUND,
802            OPSTR_AUDIO_ACCESSIBILITY_VOLUME,
803            OPSTR_READ_PHONE_NUMBERS,
804            OPSTR_REQUEST_INSTALL_PACKAGES,
805            OPSTR_PICTURE_IN_PICTURE,
806            OPSTR_INSTANT_APP_START_FOREGROUND,
807            OPSTR_ANSWER_PHONE_CALLS,
808            OPSTR_RUN_ANY_IN_BACKGROUND,
809            OPSTR_CHANGE_WIFI_STATE,
810            OPSTR_REQUEST_DELETE_PACKAGES,
811            OPSTR_BIND_ACCESSIBILITY_SERVICE,
812            OPSTR_ACCEPT_HANDOVER,
813            OPSTR_MANAGE_IPSEC_TUNNELS,
814            OPSTR_START_FOREGROUND,
815            OPSTR_BLUETOOTH_SCAN,
816    };
817
818    /**
819     * This provides a simple name for each operation to be used
820     * in debug output.
821     */
822    private static String[] sOpNames = new String[] {
823            "COARSE_LOCATION",
824            "FINE_LOCATION",
825            "GPS",
826            "VIBRATE",
827            "READ_CONTACTS",
828            "WRITE_CONTACTS",
829            "READ_CALL_LOG",
830            "WRITE_CALL_LOG",
831            "READ_CALENDAR",
832            "WRITE_CALENDAR",
833            "WIFI_SCAN",
834            "POST_NOTIFICATION",
835            "NEIGHBORING_CELLS",
836            "CALL_PHONE",
837            "READ_SMS",
838            "WRITE_SMS",
839            "RECEIVE_SMS",
840            "RECEIVE_EMERGECY_SMS",
841            "RECEIVE_MMS",
842            "RECEIVE_WAP_PUSH",
843            "SEND_SMS",
844            "READ_ICC_SMS",
845            "WRITE_ICC_SMS",
846            "WRITE_SETTINGS",
847            "SYSTEM_ALERT_WINDOW",
848            "ACCESS_NOTIFICATIONS",
849            "CAMERA",
850            "RECORD_AUDIO",
851            "PLAY_AUDIO",
852            "READ_CLIPBOARD",
853            "WRITE_CLIPBOARD",
854            "TAKE_MEDIA_BUTTONS",
855            "TAKE_AUDIO_FOCUS",
856            "AUDIO_MASTER_VOLUME",
857            "AUDIO_VOICE_VOLUME",
858            "AUDIO_RING_VOLUME",
859            "AUDIO_MEDIA_VOLUME",
860            "AUDIO_ALARM_VOLUME",
861            "AUDIO_NOTIFICATION_VOLUME",
862            "AUDIO_BLUETOOTH_VOLUME",
863            "WAKE_LOCK",
864            "MONITOR_LOCATION",
865            "MONITOR_HIGH_POWER_LOCATION",
866            "GET_USAGE_STATS",
867            "MUTE_MICROPHONE",
868            "TOAST_WINDOW",
869            "PROJECT_MEDIA",
870            "ACTIVATE_VPN",
871            "WRITE_WALLPAPER",
872            "ASSIST_STRUCTURE",
873            "ASSIST_SCREENSHOT",
874            "OP_READ_PHONE_STATE",
875            "ADD_VOICEMAIL",
876            "USE_SIP",
877            "PROCESS_OUTGOING_CALLS",
878            "USE_FINGERPRINT",
879            "BODY_SENSORS",
880            "READ_CELL_BROADCASTS",
881            "MOCK_LOCATION",
882            "READ_EXTERNAL_STORAGE",
883            "WRITE_EXTERNAL_STORAGE",
884            "TURN_ON_SCREEN",
885            "GET_ACCOUNTS",
886            "RUN_IN_BACKGROUND",
887            "AUDIO_ACCESSIBILITY_VOLUME",
888            "READ_PHONE_NUMBERS",
889            "REQUEST_INSTALL_PACKAGES",
890            "PICTURE_IN_PICTURE",
891            "INSTANT_APP_START_FOREGROUND",
892            "ANSWER_PHONE_CALLS",
893            "RUN_ANY_IN_BACKGROUND",
894            "CHANGE_WIFI_STATE",
895            "REQUEST_DELETE_PACKAGES",
896            "BIND_ACCESSIBILITY_SERVICE",
897            "ACCEPT_HANDOVER",
898            "MANAGE_IPSEC_TUNNELS",
899            "START_FOREGROUND",
900            "BLUETOOTH_SCAN",
901    };
902
903    /**
904     * This optionally maps a permission to an operation.  If there
905     * is no permission associated with an operation, it is null.
906     */
907    private static String[] sOpPerms = new String[] {
908            android.Manifest.permission.ACCESS_COARSE_LOCATION,
909            android.Manifest.permission.ACCESS_FINE_LOCATION,
910            null,
911            android.Manifest.permission.VIBRATE,
912            android.Manifest.permission.READ_CONTACTS,
913            android.Manifest.permission.WRITE_CONTACTS,
914            android.Manifest.permission.READ_CALL_LOG,
915            android.Manifest.permission.WRITE_CALL_LOG,
916            android.Manifest.permission.READ_CALENDAR,
917            android.Manifest.permission.WRITE_CALENDAR,
918            android.Manifest.permission.ACCESS_WIFI_STATE,
919            null, // no permission required for notifications
920            null, // neighboring cells shares the coarse location perm
921            android.Manifest.permission.CALL_PHONE,
922            android.Manifest.permission.READ_SMS,
923            null, // no permission required for writing sms
924            android.Manifest.permission.RECEIVE_SMS,
925            android.Manifest.permission.RECEIVE_EMERGENCY_BROADCAST,
926            android.Manifest.permission.RECEIVE_MMS,
927            android.Manifest.permission.RECEIVE_WAP_PUSH,
928            android.Manifest.permission.SEND_SMS,
929            android.Manifest.permission.READ_SMS,
930            null, // no permission required for writing icc sms
931            android.Manifest.permission.WRITE_SETTINGS,
932            android.Manifest.permission.SYSTEM_ALERT_WINDOW,
933            android.Manifest.permission.ACCESS_NOTIFICATIONS,
934            android.Manifest.permission.CAMERA,
935            android.Manifest.permission.RECORD_AUDIO,
936            null, // no permission for playing audio
937            null, // no permission for reading clipboard
938            null, // no permission for writing clipboard
939            null, // no permission for taking media buttons
940            null, // no permission for taking audio focus
941            null, // no permission for changing master volume
942            null, // no permission for changing voice volume
943            null, // no permission for changing ring volume
944            null, // no permission for changing media volume
945            null, // no permission for changing alarm volume
946            null, // no permission for changing notification volume
947            null, // no permission for changing bluetooth volume
948            android.Manifest.permission.WAKE_LOCK,
949            null, // no permission for generic location monitoring
950            null, // no permission for high power location monitoring
951            android.Manifest.permission.PACKAGE_USAGE_STATS,
952            null, // no permission for muting/unmuting microphone
953            null, // no permission for displaying toasts
954            null, // no permission for projecting media
955            null, // no permission for activating vpn
956            null, // no permission for supporting wallpaper
957            null, // no permission for receiving assist structure
958            null, // no permission for receiving assist screenshot
959            Manifest.permission.READ_PHONE_STATE,
960            Manifest.permission.ADD_VOICEMAIL,
961            Manifest.permission.USE_SIP,
962            Manifest.permission.PROCESS_OUTGOING_CALLS,
963            Manifest.permission.USE_FINGERPRINT,
964            Manifest.permission.BODY_SENSORS,
965            Manifest.permission.READ_CELL_BROADCASTS,
966            null,
967            Manifest.permission.READ_EXTERNAL_STORAGE,
968            Manifest.permission.WRITE_EXTERNAL_STORAGE,
969            null, // no permission for turning the screen on
970            Manifest.permission.GET_ACCOUNTS,
971            null, // no permission for running in background
972            null, // no permission for changing accessibility volume
973            Manifest.permission.READ_PHONE_NUMBERS,
974            Manifest.permission.REQUEST_INSTALL_PACKAGES,
975            null, // no permission for entering picture-in-picture on hide
976            Manifest.permission.INSTANT_APP_FOREGROUND_SERVICE,
977            Manifest.permission.ANSWER_PHONE_CALLS,
978            null, // no permission for OP_RUN_ANY_IN_BACKGROUND
979            Manifest.permission.CHANGE_WIFI_STATE,
980            Manifest.permission.REQUEST_DELETE_PACKAGES,
981            Manifest.permission.BIND_ACCESSIBILITY_SERVICE,
982            Manifest.permission.ACCEPT_HANDOVER,
983            null, // no permission for OP_MANAGE_IPSEC_TUNNELS
984            Manifest.permission.FOREGROUND_SERVICE,
985            null, // no permission for OP_BLUETOOTH_SCAN
986    };
987
988    /**
989     * Specifies whether an Op should be restricted by a user restriction.
990     * Each Op should be filled with a restriction string from UserManager or
991     * null to specify it is not affected by any user restriction.
992     */
993    private static String[] sOpRestrictions = new String[] {
994            UserManager.DISALLOW_SHARE_LOCATION, //COARSE_LOCATION
995            UserManager.DISALLOW_SHARE_LOCATION, //FINE_LOCATION
996            UserManager.DISALLOW_SHARE_LOCATION, //GPS
997            null, //VIBRATE
998            null, //READ_CONTACTS
999            null, //WRITE_CONTACTS
1000            UserManager.DISALLOW_OUTGOING_CALLS, //READ_CALL_LOG
1001            UserManager.DISALLOW_OUTGOING_CALLS, //WRITE_CALL_LOG
1002            null, //READ_CALENDAR
1003            null, //WRITE_CALENDAR
1004            UserManager.DISALLOW_SHARE_LOCATION, //WIFI_SCAN
1005            null, //POST_NOTIFICATION
1006            null, //NEIGHBORING_CELLS
1007            null, //CALL_PHONE
1008            UserManager.DISALLOW_SMS, //READ_SMS
1009            UserManager.DISALLOW_SMS, //WRITE_SMS
1010            UserManager.DISALLOW_SMS, //RECEIVE_SMS
1011            null, //RECEIVE_EMERGENCY_SMS
1012            UserManager.DISALLOW_SMS, //RECEIVE_MMS
1013            null, //RECEIVE_WAP_PUSH
1014            UserManager.DISALLOW_SMS, //SEND_SMS
1015            UserManager.DISALLOW_SMS, //READ_ICC_SMS
1016            UserManager.DISALLOW_SMS, //WRITE_ICC_SMS
1017            null, //WRITE_SETTINGS
1018            UserManager.DISALLOW_CREATE_WINDOWS, //SYSTEM_ALERT_WINDOW
1019            null, //ACCESS_NOTIFICATIONS
1020            UserManager.DISALLOW_CAMERA, //CAMERA
1021            UserManager.DISALLOW_RECORD_AUDIO, //RECORD_AUDIO
1022            null, //PLAY_AUDIO
1023            null, //READ_CLIPBOARD
1024            null, //WRITE_CLIPBOARD
1025            null, //TAKE_MEDIA_BUTTONS
1026            null, //TAKE_AUDIO_FOCUS
1027            UserManager.DISALLOW_ADJUST_VOLUME, //AUDIO_MASTER_VOLUME
1028            UserManager.DISALLOW_ADJUST_VOLUME, //AUDIO_VOICE_VOLUME
1029            UserManager.DISALLOW_ADJUST_VOLUME, //AUDIO_RING_VOLUME
1030            UserManager.DISALLOW_ADJUST_VOLUME, //AUDIO_MEDIA_VOLUME
1031            UserManager.DISALLOW_ADJUST_VOLUME, //AUDIO_ALARM_VOLUME
1032            UserManager.DISALLOW_ADJUST_VOLUME, //AUDIO_NOTIFICATION_VOLUME
1033            UserManager.DISALLOW_ADJUST_VOLUME, //AUDIO_BLUETOOTH_VOLUME
1034            null, //WAKE_LOCK
1035            UserManager.DISALLOW_SHARE_LOCATION, //MONITOR_LOCATION
1036            UserManager.DISALLOW_SHARE_LOCATION, //MONITOR_HIGH_POWER_LOCATION
1037            null, //GET_USAGE_STATS
1038            UserManager.DISALLOW_UNMUTE_MICROPHONE, // MUTE_MICROPHONE
1039            UserManager.DISALLOW_CREATE_WINDOWS, // TOAST_WINDOW
1040            null, //PROJECT_MEDIA
1041            null, // ACTIVATE_VPN
1042            UserManager.DISALLOW_WALLPAPER, // WRITE_WALLPAPER
1043            null, // ASSIST_STRUCTURE
1044            null, // ASSIST_SCREENSHOT
1045            null, // READ_PHONE_STATE
1046            null, // ADD_VOICEMAIL
1047            null, // USE_SIP
1048            null, // PROCESS_OUTGOING_CALLS
1049            null, // USE_FINGERPRINT
1050            null, // BODY_SENSORS
1051            null, // READ_CELL_BROADCASTS
1052            null, // MOCK_LOCATION
1053            null, // READ_EXTERNAL_STORAGE
1054            null, // WRITE_EXTERNAL_STORAGE
1055            null, // TURN_ON_SCREEN
1056            null, // GET_ACCOUNTS
1057            null, // RUN_IN_BACKGROUND
1058            UserManager.DISALLOW_ADJUST_VOLUME, //AUDIO_ACCESSIBILITY_VOLUME
1059            null, // READ_PHONE_NUMBERS
1060            null, // REQUEST_INSTALL_PACKAGES
1061            null, // ENTER_PICTURE_IN_PICTURE_ON_HIDE
1062            null, // INSTANT_APP_START_FOREGROUND
1063            null, // ANSWER_PHONE_CALLS
1064            null, // OP_RUN_ANY_IN_BACKGROUND
1065            null, // OP_CHANGE_WIFI_STATE
1066            null, // REQUEST_DELETE_PACKAGES
1067            null, // OP_BIND_ACCESSIBILITY_SERVICE
1068            null, // ACCEPT_HANDOVER
1069            null, // MANAGE_IPSEC_TUNNELS
1070            null, // START_FOREGROUND
1071            null, // maybe should be UserManager.DISALLOW_SHARE_LOCATION, //BLUETOOTH_SCAN
1072    };
1073
1074    /**
1075     * This specifies whether each option should allow the system
1076     * (and system ui) to bypass the user restriction when active.
1077     */
1078    private static boolean[] sOpAllowSystemRestrictionBypass = new boolean[] {
1079            true, //COARSE_LOCATION
1080            true, //FINE_LOCATION
1081            false, //GPS
1082            false, //VIBRATE
1083            false, //READ_CONTACTS
1084            false, //WRITE_CONTACTS
1085            false, //READ_CALL_LOG
1086            false, //WRITE_CALL_LOG
1087            false, //READ_CALENDAR
1088            false, //WRITE_CALENDAR
1089            true, //WIFI_SCAN
1090            false, //POST_NOTIFICATION
1091            false, //NEIGHBORING_CELLS
1092            false, //CALL_PHONE
1093            false, //READ_SMS
1094            false, //WRITE_SMS
1095            false, //RECEIVE_SMS
1096            false, //RECEIVE_EMERGECY_SMS
1097            false, //RECEIVE_MMS
1098            false, //RECEIVE_WAP_PUSH
1099            false, //SEND_SMS
1100            false, //READ_ICC_SMS
1101            false, //WRITE_ICC_SMS
1102            false, //WRITE_SETTINGS
1103            true, //SYSTEM_ALERT_WINDOW
1104            false, //ACCESS_NOTIFICATIONS
1105            false, //CAMERA
1106            false, //RECORD_AUDIO
1107            false, //PLAY_AUDIO
1108            false, //READ_CLIPBOARD
1109            false, //WRITE_CLIPBOARD
1110            false, //TAKE_MEDIA_BUTTONS
1111            false, //TAKE_AUDIO_FOCUS
1112            false, //AUDIO_MASTER_VOLUME
1113            false, //AUDIO_VOICE_VOLUME
1114            false, //AUDIO_RING_VOLUME
1115            false, //AUDIO_MEDIA_VOLUME
1116            false, //AUDIO_ALARM_VOLUME
1117            false, //AUDIO_NOTIFICATION_VOLUME
1118            false, //AUDIO_BLUETOOTH_VOLUME
1119            false, //WAKE_LOCK
1120            false, //MONITOR_LOCATION
1121            false, //MONITOR_HIGH_POWER_LOCATION
1122            false, //GET_USAGE_STATS
1123            false, //MUTE_MICROPHONE
1124            true, //TOAST_WINDOW
1125            false, //PROJECT_MEDIA
1126            false, //ACTIVATE_VPN
1127            false, //WALLPAPER
1128            false, //ASSIST_STRUCTURE
1129            false, //ASSIST_SCREENSHOT
1130            false, //READ_PHONE_STATE
1131            false, //ADD_VOICEMAIL
1132            false, // USE_SIP
1133            false, // PROCESS_OUTGOING_CALLS
1134            false, // USE_FINGERPRINT
1135            false, // BODY_SENSORS
1136            false, // READ_CELL_BROADCASTS
1137            false, // MOCK_LOCATION
1138            false, // READ_EXTERNAL_STORAGE
1139            false, // WRITE_EXTERNAL_STORAGE
1140            false, // TURN_ON_SCREEN
1141            false, // GET_ACCOUNTS
1142            false, // RUN_IN_BACKGROUND
1143            false, // AUDIO_ACCESSIBILITY_VOLUME
1144            false, // READ_PHONE_NUMBERS
1145            false, // REQUEST_INSTALL_PACKAGES
1146            false, // ENTER_PICTURE_IN_PICTURE_ON_HIDE
1147            false, // INSTANT_APP_START_FOREGROUND
1148            false, // ANSWER_PHONE_CALLS
1149            false, // OP_RUN_ANY_IN_BACKGROUND
1150            false, // OP_CHANGE_WIFI_STATE
1151            false, // OP_REQUEST_DELETE_PACKAGES
1152            false, // OP_BIND_ACCESSIBILITY_SERVICE
1153            false, // ACCEPT_HANDOVER
1154            false, // MANAGE_IPSEC_HANDOVERS
1155            false, // START_FOREGROUND
1156            true, // BLUETOOTH_SCAN
1157    };
1158
1159    /**
1160     * This specifies the default mode for each operation.
1161     */
1162    private static int[] sOpDefaultMode = new int[] {
1163            AppOpsManager.MODE_ALLOWED,
1164            AppOpsManager.MODE_ALLOWED,
1165            AppOpsManager.MODE_ALLOWED,
1166            AppOpsManager.MODE_ALLOWED,
1167            AppOpsManager.MODE_ALLOWED,
1168            AppOpsManager.MODE_ALLOWED,
1169            AppOpsManager.MODE_ALLOWED,
1170            AppOpsManager.MODE_ALLOWED,
1171            AppOpsManager.MODE_ALLOWED,
1172            AppOpsManager.MODE_ALLOWED,
1173            AppOpsManager.MODE_ALLOWED,
1174            AppOpsManager.MODE_ALLOWED,
1175            AppOpsManager.MODE_ALLOWED,
1176            AppOpsManager.MODE_ALLOWED,
1177            AppOpsManager.MODE_ALLOWED,
1178            AppOpsManager.MODE_IGNORED, // OP_WRITE_SMS
1179            AppOpsManager.MODE_ALLOWED,
1180            AppOpsManager.MODE_ALLOWED,
1181            AppOpsManager.MODE_ALLOWED,
1182            AppOpsManager.MODE_ALLOWED,
1183            AppOpsManager.MODE_ALLOWED,
1184            AppOpsManager.MODE_ALLOWED,
1185            AppOpsManager.MODE_ALLOWED,
1186            AppOpsManager.MODE_DEFAULT, // OP_WRITE_SETTINGS
1187            AppOpsManager.MODE_DEFAULT, // OP_SYSTEM_ALERT_WINDOW
1188            AppOpsManager.MODE_ALLOWED,
1189            AppOpsManager.MODE_ALLOWED,
1190            AppOpsManager.MODE_ALLOWED,
1191            AppOpsManager.MODE_ALLOWED,
1192            AppOpsManager.MODE_ALLOWED,
1193            AppOpsManager.MODE_ALLOWED,
1194            AppOpsManager.MODE_ALLOWED,
1195            AppOpsManager.MODE_ALLOWED,
1196            AppOpsManager.MODE_ALLOWED,
1197            AppOpsManager.MODE_ALLOWED,
1198            AppOpsManager.MODE_ALLOWED,
1199            AppOpsManager.MODE_ALLOWED,
1200            AppOpsManager.MODE_ALLOWED,
1201            AppOpsManager.MODE_ALLOWED,
1202            AppOpsManager.MODE_ALLOWED,
1203            AppOpsManager.MODE_ALLOWED,
1204            AppOpsManager.MODE_ALLOWED,
1205            AppOpsManager.MODE_ALLOWED,
1206            AppOpsManager.MODE_DEFAULT, // OP_GET_USAGE_STATS
1207            AppOpsManager.MODE_ALLOWED,
1208            AppOpsManager.MODE_ALLOWED,
1209            AppOpsManager.MODE_IGNORED, // OP_PROJECT_MEDIA
1210            AppOpsManager.MODE_IGNORED, // OP_ACTIVATE_VPN
1211            AppOpsManager.MODE_ALLOWED,
1212            AppOpsManager.MODE_ALLOWED,
1213            AppOpsManager.MODE_ALLOWED,
1214            AppOpsManager.MODE_ALLOWED,
1215            AppOpsManager.MODE_ALLOWED,
1216            AppOpsManager.MODE_ALLOWED,
1217            AppOpsManager.MODE_ALLOWED,
1218            AppOpsManager.MODE_ALLOWED,
1219            AppOpsManager.MODE_ALLOWED,
1220            AppOpsManager.MODE_ALLOWED,
1221            AppOpsManager.MODE_ERRORED,  // OP_MOCK_LOCATION
1222            AppOpsManager.MODE_ALLOWED,
1223            AppOpsManager.MODE_ALLOWED,
1224            AppOpsManager.MODE_ALLOWED,  // OP_TURN_ON_SCREEN
1225            AppOpsManager.MODE_ALLOWED,
1226            AppOpsManager.MODE_ALLOWED,  // OP_RUN_IN_BACKGROUND
1227            AppOpsManager.MODE_ALLOWED,  // OP_AUDIO_ACCESSIBILITY_VOLUME
1228            AppOpsManager.MODE_ALLOWED,
1229            AppOpsManager.MODE_DEFAULT,  // OP_REQUEST_INSTALL_PACKAGES
1230            AppOpsManager.MODE_ALLOWED,  // OP_PICTURE_IN_PICTURE
1231            AppOpsManager.MODE_DEFAULT,  // OP_INSTANT_APP_START_FOREGROUND
1232            AppOpsManager.MODE_ALLOWED,  // ANSWER_PHONE_CALLS
1233            AppOpsManager.MODE_ALLOWED,  // OP_RUN_ANY_IN_BACKGROUND
1234            AppOpsManager.MODE_ALLOWED,  // OP_CHANGE_WIFI_STATE
1235            AppOpsManager.MODE_ALLOWED,  // REQUEST_DELETE_PACKAGES
1236            AppOpsManager.MODE_ALLOWED,  // OP_BIND_ACCESSIBILITY_SERVICE
1237            AppOpsManager.MODE_ALLOWED,  // ACCEPT_HANDOVER
1238            AppOpsManager.MODE_ERRORED,  // MANAGE_IPSEC_TUNNELS
1239            AppOpsManager.MODE_ALLOWED,  // OP_START_FOREGROUND
1240            AppOpsManager.MODE_ALLOWED,  // OP_BLUETOOTH_SCAN
1241    };
1242
1243    /**
1244     * This specifies whether each option is allowed to be reset
1245     * when resetting all app preferences.  Disable reset for
1246     * app ops that are under strong control of some part of the
1247     * system (such as OP_WRITE_SMS, which should be allowed only
1248     * for whichever app is selected as the current SMS app).
1249     */
1250    private static boolean[] sOpDisableReset = new boolean[] {
1251            false,
1252            false,
1253            false,
1254            false,
1255            false,
1256            false,
1257            false,
1258            false,
1259            false,
1260            false,
1261            false,
1262            false,
1263            false,
1264            false,
1265            false,
1266            true,      // OP_WRITE_SMS
1267            false,
1268            false,
1269            false,
1270            false,
1271            false,
1272            false,
1273            false,
1274            false,
1275            false,
1276            false,
1277            false,
1278            false,
1279            false,
1280            false,
1281            false,
1282            false,
1283            false,
1284            false,
1285            false,
1286            false,
1287            false,
1288            false,
1289            false,
1290            false,
1291            false,
1292            false,
1293            false,
1294            false,
1295            false,
1296            false,
1297            false,
1298            false,
1299            false,
1300            false,
1301            false,
1302            false,
1303            false,
1304            false,
1305            false,
1306            false,
1307            false,
1308            false,
1309            false,
1310            false,
1311            false,
1312            false,
1313            false,
1314            false,
1315            false, // OP_AUDIO_ACCESSIBILITY_VOLUME
1316            false,
1317            false, // OP_REQUEST_INSTALL_PACKAGES
1318            false, // OP_PICTURE_IN_PICTURE
1319            false,
1320            false, // ANSWER_PHONE_CALLS
1321            false, // OP_RUN_ANY_IN_BACKGROUND
1322            false, // OP_CHANGE_WIFI_STATE
1323            false, // OP_REQUEST_DELETE_PACKAGES
1324            false, // OP_BIND_ACCESSIBILITY_SERVICE
1325            false, // ACCEPT_HANDOVER
1326            false, // MANAGE_IPSEC_TUNNELS
1327            false, // START_FOREGROUND
1328            false, // BLUETOOTH_SCAN
1329    };
1330
1331    /**
1332     * Mapping from an app op name to the app op code.
1333     */
1334    private static HashMap<String, Integer> sOpStrToOp = new HashMap<>();
1335
1336    /**
1337     * Mapping from a permission to the corresponding app op.
1338     */
1339    private static HashMap<String, Integer> sPermToOp = new HashMap<>();
1340
1341    static {
1342        if (sOpToSwitch.length != _NUM_OP) {
1343            throw new IllegalStateException("sOpToSwitch length " + sOpToSwitch.length
1344                    + " should be " + _NUM_OP);
1345        }
1346        if (sOpToString.length != _NUM_OP) {
1347            throw new IllegalStateException("sOpToString length " + sOpToString.length
1348                    + " should be " + _NUM_OP);
1349        }
1350        if (sOpNames.length != _NUM_OP) {
1351            throw new IllegalStateException("sOpNames length " + sOpNames.length
1352                    + " should be " + _NUM_OP);
1353        }
1354        if (sOpPerms.length != _NUM_OP) {
1355            throw new IllegalStateException("sOpPerms length " + sOpPerms.length
1356                    + " should be " + _NUM_OP);
1357        }
1358        if (sOpDefaultMode.length != _NUM_OP) {
1359            throw new IllegalStateException("sOpDefaultMode length " + sOpDefaultMode.length
1360                    + " should be " + _NUM_OP);
1361        }
1362        if (sOpDisableReset.length != _NUM_OP) {
1363            throw new IllegalStateException("sOpDisableReset length " + sOpDisableReset.length
1364                    + " should be " + _NUM_OP);
1365        }
1366        if (sOpRestrictions.length != _NUM_OP) {
1367            throw new IllegalStateException("sOpRestrictions length " + sOpRestrictions.length
1368                    + " should be " + _NUM_OP);
1369        }
1370        if (sOpAllowSystemRestrictionBypass.length != _NUM_OP) {
1371            throw new IllegalStateException("sOpAllowSYstemRestrictionsBypass length "
1372                    + sOpRestrictions.length + " should be " + _NUM_OP);
1373        }
1374        for (int i=0; i<_NUM_OP; i++) {
1375            if (sOpToString[i] != null) {
1376                sOpStrToOp.put(sOpToString[i], i);
1377            }
1378        }
1379        for (int op : RUNTIME_AND_APPOP_PERMISSIONS_OPS) {
1380            if (sOpPerms[op] != null) {
1381                sPermToOp.put(sOpPerms[op], op);
1382            }
1383        }
1384    }
1385
1386    /**
1387     * Retrieve the op switch that controls the given operation.
1388     * @hide
1389     */
1390    public static int opToSwitch(int op) {
1391        return sOpToSwitch[op];
1392    }
1393
1394    /**
1395     * Retrieve a non-localized name for the operation, for debugging output.
1396     * @hide
1397     */
1398    public static String opToName(int op) {
1399        if (op == OP_NONE) return "NONE";
1400        return op < sOpNames.length ? sOpNames[op] : ("Unknown(" + op + ")");
1401    }
1402
1403    /**
1404     * @hide
1405     */
1406    public static int strDebugOpToOp(String op) {
1407        for (int i=0; i<sOpNames.length; i++) {
1408            if (sOpNames[i].equals(op)) {
1409                return i;
1410            }
1411        }
1412        throw new IllegalArgumentException("Unknown operation string: " + op);
1413    }
1414
1415    /**
1416     * Retrieve the permission associated with an operation, or null if there is not one.
1417     * @hide
1418     */
1419    public static String opToPermission(int op) {
1420        return sOpPerms[op];
1421    }
1422
1423    /**
1424     * Retrieve the user restriction associated with an operation, or null if there is not one.
1425     * @hide
1426     */
1427    public static String opToRestriction(int op) {
1428        return sOpRestrictions[op];
1429    }
1430
1431    /**
1432     * Retrieve the app op code for a permission, or null if there is not one.
1433     * This API is intended to be used for mapping runtime or appop permissions
1434     * to the corresponding app op.
1435     * @hide
1436     */
1437    public static int permissionToOpCode(String permission) {
1438        Integer boxedOpCode = sPermToOp.get(permission);
1439        return boxedOpCode != null ? boxedOpCode : OP_NONE;
1440    }
1441
1442    /**
1443     * Retrieve whether the op allows the system (and system ui) to
1444     * bypass the user restriction.
1445     * @hide
1446     */
1447    public static boolean opAllowSystemBypassRestriction(int op) {
1448        return sOpAllowSystemRestrictionBypass[op];
1449    }
1450
1451    /**
1452     * Retrieve the default mode for the operation.
1453     * @hide
1454     */
1455    public static int opToDefaultMode(int op) {
1456        return sOpDefaultMode[op];
1457    }
1458
1459    /**
1460     * Retrieve the human readable mode.
1461     * @hide
1462     */
1463    public static String modeToName(int mode) {
1464        if (mode >= 0 && mode < MODE_NAMES.length) {
1465            return MODE_NAMES[mode];
1466        }
1467        return "mode=" + mode;
1468    }
1469
1470    /**
1471     * Retrieve whether the op allows itself to be reset.
1472     * @hide
1473     */
1474    public static boolean opAllowsReset(int op) {
1475        return !sOpDisableReset[op];
1476    }
1477
1478    /**
1479     * Class holding all of the operation information associated with an app.
1480     * @hide
1481     */
1482    public static class PackageOps implements Parcelable {
1483        private final String mPackageName;
1484        private final int mUid;
1485        private final List<OpEntry> mEntries;
1486
1487        public PackageOps(String packageName, int uid, List<OpEntry> entries) {
1488            mPackageName = packageName;
1489            mUid = uid;
1490            mEntries = entries;
1491        }
1492
1493        public String getPackageName() {
1494            return mPackageName;
1495        }
1496
1497        public int getUid() {
1498            return mUid;
1499        }
1500
1501        public List<OpEntry> getOps() {
1502            return mEntries;
1503        }
1504
1505        @Override
1506        public int describeContents() {
1507            return 0;
1508        }
1509
1510        @Override
1511        public void writeToParcel(Parcel dest, int flags) {
1512            dest.writeString(mPackageName);
1513            dest.writeInt(mUid);
1514            dest.writeInt(mEntries.size());
1515            for (int i=0; i<mEntries.size(); i++) {
1516                mEntries.get(i).writeToParcel(dest, flags);
1517            }
1518        }
1519
1520        PackageOps(Parcel source) {
1521            mPackageName = source.readString();
1522            mUid = source.readInt();
1523            mEntries = new ArrayList<OpEntry>();
1524            final int N = source.readInt();
1525            for (int i=0; i<N; i++) {
1526                mEntries.add(OpEntry.CREATOR.createFromParcel(source));
1527            }
1528        }
1529
1530        public static final Creator<PackageOps> CREATOR = new Creator<PackageOps>() {
1531            @Override public PackageOps createFromParcel(Parcel source) {
1532                return new PackageOps(source);
1533            }
1534
1535            @Override public PackageOps[] newArray(int size) {
1536                return new PackageOps[size];
1537            }
1538        };
1539    }
1540
1541    /**
1542     * Class holding the information about one unique operation of an application.
1543     * @hide
1544     */
1545    public static class OpEntry implements Parcelable {
1546        private final int mOp;
1547        private final int mMode;
1548        private final long[] mTimes;
1549        private final long[] mRejectTimes;
1550        private final int mDuration;
1551        private final int mProxyUid;
1552        private final String mProxyPackageName;
1553
1554        public OpEntry(int op, int mode, long time, long rejectTime, int duration,
1555                int proxyUid, String proxyPackage) {
1556            mOp = op;
1557            mMode = mode;
1558            mTimes = new long[_NUM_UID_STATE];
1559            mRejectTimes = new long[_NUM_UID_STATE];
1560            mTimes[0] = time;
1561            mRejectTimes[0] = rejectTime;
1562            mDuration = duration;
1563            mProxyUid = proxyUid;
1564            mProxyPackageName = proxyPackage;
1565        }
1566
1567        public OpEntry(int op, int mode, long[] times, long[] rejectTimes, int duration,
1568                int proxyUid, String proxyPackage) {
1569            mOp = op;
1570            mMode = mode;
1571            mTimes = new long[_NUM_UID_STATE];
1572            mRejectTimes = new long[_NUM_UID_STATE];
1573            System.arraycopy(times, 0, mTimes, 0, _NUM_UID_STATE);
1574            System.arraycopy(rejectTimes, 0, mRejectTimes, 0, _NUM_UID_STATE);
1575            mDuration = duration;
1576            mProxyUid = proxyUid;
1577            mProxyPackageName = proxyPackage;
1578        }
1579
1580        public int getOp() {
1581            return mOp;
1582        }
1583
1584        public int getMode() {
1585            return mMode;
1586        }
1587
1588        public long getTime() {
1589            return maxTime(mTimes, 0, _NUM_UID_STATE);
1590        }
1591
1592        public long getLastAccessTime() {
1593            return maxTime(mTimes, 0, _NUM_UID_STATE);
1594        }
1595
1596        public long getLastAccessForegroundTime() {
1597            return maxTime(mTimes, UID_STATE_PERSISTENT, UID_STATE_FOREGROUND_SERVICE + 1);
1598        }
1599
1600        public long getLastAccessBackgroundTime() {
1601            return maxTime(mTimes, UID_STATE_FOREGROUND_SERVICE + 1, _NUM_UID_STATE);
1602        }
1603
1604        public long getLastTimeFor(int uidState) {
1605            return mTimes[uidState];
1606        }
1607
1608        public long getRejectTime() {
1609            return maxTime(mRejectTimes, 0, _NUM_UID_STATE);
1610        }
1611
1612        public long getLastRejectTime() {
1613            return maxTime(mRejectTimes, 0, _NUM_UID_STATE);
1614        }
1615
1616        public long getLastRejectForegroundTime() {
1617            return maxTime(mRejectTimes, UID_STATE_PERSISTENT, UID_STATE_FOREGROUND_SERVICE + 1);
1618        }
1619
1620        public long getLastRejectBackgroundTime() {
1621            return maxTime(mRejectTimes, UID_STATE_FOREGROUND_SERVICE + 1, _NUM_UID_STATE);
1622        }
1623
1624        public long getLastRejectTimeFor(int uidState) {
1625            return mRejectTimes[uidState];
1626        }
1627
1628        public boolean isRunning() {
1629            return mDuration == -1;
1630        }
1631
1632        public int getDuration() {
1633            return mDuration;
1634        }
1635
1636        public int getProxyUid() {
1637            return  mProxyUid;
1638        }
1639
1640        public String getProxyPackageName() {
1641            return mProxyPackageName;
1642        }
1643
1644        @Override
1645        public int describeContents() {
1646            return 0;
1647        }
1648
1649        @Override
1650        public void writeToParcel(Parcel dest, int flags) {
1651            dest.writeInt(mOp);
1652            dest.writeInt(mMode);
1653            dest.writeLongArray(mTimes);
1654            dest.writeLongArray(mRejectTimes);
1655            dest.writeInt(mDuration);
1656            dest.writeInt(mProxyUid);
1657            dest.writeString(mProxyPackageName);
1658        }
1659
1660        OpEntry(Parcel source) {
1661            mOp = source.readInt();
1662            mMode = source.readInt();
1663            mTimes = source.createLongArray();
1664            mRejectTimes = source.createLongArray();
1665            mDuration = source.readInt();
1666            mProxyUid = source.readInt();
1667            mProxyPackageName = source.readString();
1668        }
1669
1670        public static final Creator<OpEntry> CREATOR = new Creator<OpEntry>() {
1671            @Override public OpEntry createFromParcel(Parcel source) {
1672                return new OpEntry(source);
1673            }
1674
1675            @Override public OpEntry[] newArray(int size) {
1676                return new OpEntry[size];
1677            }
1678        };
1679    }
1680
1681    /**
1682     * Callback for notification of changes to operation state.
1683     */
1684    public interface OnOpChangedListener {
1685        public void onOpChanged(String op, String packageName);
1686    }
1687
1688    /**
1689     * Callback for notification of changes to operation active state.
1690     *
1691     * @hide
1692     */
1693    @TestApi
1694    public interface OnOpActiveChangedListener {
1695        /**
1696         * Called when the active state of an app op changes.
1697         *
1698         * @param code The op code.
1699         * @param uid The UID performing the operation.
1700         * @param packageName The package performing the operation.
1701         * @param active Whether the operation became active or inactive.
1702         */
1703        void onOpActiveChanged(int code, int uid, String packageName, boolean active);
1704    }
1705
1706    /**
1707     * Callback for notification of changes to operation state.
1708     * This allows you to see the raw op codes instead of strings.
1709     * @hide
1710     */
1711    public static class OnOpChangedInternalListener implements OnOpChangedListener {
1712        public void onOpChanged(String op, String packageName) { }
1713        public void onOpChanged(int op, String packageName) { }
1714    }
1715
1716    AppOpsManager(Context context, IAppOpsService service) {
1717        mContext = context;
1718        mService = service;
1719    }
1720
1721    /**
1722     * Retrieve current operation state for all applications.
1723     *
1724     * @param ops The set of operations you are interested in, or null if you want all of them.
1725     * @hide
1726     */
1727    @RequiresPermission(android.Manifest.permission.GET_APP_OPS_STATS)
1728    public List<AppOpsManager.PackageOps> getPackagesForOps(int[] ops) {
1729        try {
1730            return mService.getPackagesForOps(ops);
1731        } catch (RemoteException e) {
1732            throw e.rethrowFromSystemServer();
1733        }
1734    }
1735
1736    /**
1737     * Retrieve current operation state for one application.
1738     *
1739     * @param uid The uid of the application of interest.
1740     * @param packageName The name of the application of interest.
1741     * @param ops The set of operations you are interested in, or null if you want all of them.
1742     * @hide
1743     */
1744    @RequiresPermission(android.Manifest.permission.GET_APP_OPS_STATS)
1745    public List<AppOpsManager.PackageOps> getOpsForPackage(int uid, String packageName, int[] ops) {
1746        try {
1747            return mService.getOpsForPackage(uid, packageName, ops);
1748        } catch (RemoteException e) {
1749            throw e.rethrowFromSystemServer();
1750        }
1751    }
1752
1753    /**
1754     * Sets given app op in the specified mode for app ops in the UID.
1755     * This applies to all apps currently in the UID or installed in
1756     * this UID in the future.
1757     *
1758     * @param code The app op.
1759     * @param uid The UID for which to set the app.
1760     * @param mode The app op mode to set.
1761     * @hide
1762     */
1763    @RequiresPermission(android.Manifest.permission.MANAGE_APP_OPS_MODES)
1764    public void setUidMode(int code, int uid, int mode) {
1765        try {
1766            mService.setUidMode(code, uid, mode);
1767        } catch (RemoteException e) {
1768            throw e.rethrowFromSystemServer();
1769        }
1770    }
1771
1772    /**
1773     * Sets given app op in the specified mode for app ops in the UID.
1774     * This applies to all apps currently in the UID or installed in
1775     * this UID in the future.
1776     *
1777     * @param appOp The app op.
1778     * @param uid The UID for which to set the app.
1779     * @param mode The app op mode to set.
1780     * @hide
1781     */
1782    @SystemApi
1783    @RequiresPermission(android.Manifest.permission.MANAGE_APP_OPS_MODES)
1784    public void setUidMode(String appOp, int uid, int mode) {
1785        try {
1786            mService.setUidMode(AppOpsManager.strOpToOp(appOp), uid, mode);
1787        } catch (RemoteException e) {
1788            throw e.rethrowFromSystemServer();
1789        }
1790    }
1791
1792    /** @hide */
1793    public void setUserRestriction(int code, boolean restricted, IBinder token) {
1794        setUserRestriction(code, restricted, token, /*exceptionPackages*/null);
1795    }
1796
1797    /** @hide */
1798    public void setUserRestriction(int code, boolean restricted, IBinder token,
1799            String[] exceptionPackages) {
1800        setUserRestrictionForUser(code, restricted, token, exceptionPackages, mContext.getUserId());
1801    }
1802
1803    /** @hide */
1804    public void setUserRestrictionForUser(int code, boolean restricted, IBinder token,
1805            String[] exceptionPackages, int userId) {
1806        try {
1807            mService.setUserRestriction(code, restricted, token, userId, exceptionPackages);
1808        } catch (RemoteException e) {
1809            throw e.rethrowFromSystemServer();
1810        }
1811    }
1812
1813    /** @hide */
1814    @TestApi
1815    @RequiresPermission(android.Manifest.permission.MANAGE_APP_OPS_MODES)
1816    public void setMode(int code, int uid, String packageName, int mode) {
1817        try {
1818            mService.setMode(code, uid, packageName, mode);
1819        } catch (RemoteException e) {
1820            throw e.rethrowFromSystemServer();
1821        }
1822    }
1823
1824    /**
1825     * Change the operating mode for the given op in the given app package.  You must pass
1826     * in both the uid and name of the application whose mode is being modified; if these
1827     * do not match, the modification will not be applied.
1828     *
1829     * @param op The operation to modify.  One of the OPSTR_* constants.
1830     * @param uid The user id of the application whose mode will be changed.
1831     * @param packageName The name of the application package name whose mode will
1832     * be changed.
1833     * @hide
1834     */
1835    @SystemApi
1836    @RequiresPermission(android.Manifest.permission.MANAGE_APP_OPS_MODES)
1837    public void setMode(String op, int uid, String packageName, int mode) {
1838        try {
1839            mService.setMode(strOpToOp(op), uid, packageName, mode);
1840        } catch (RemoteException e) {
1841            throw e.rethrowFromSystemServer();
1842        }
1843    }
1844
1845    /**
1846     * Set a non-persisted restriction on an audio operation at a stream-level.
1847     * Restrictions are temporary additional constraints imposed on top of the persisted rules
1848     * defined by {@link #setMode}.
1849     *
1850     * @param code The operation to restrict.
1851     * @param usage The {@link android.media.AudioAttributes} usage value.
1852     * @param mode The restriction mode (MODE_IGNORED,MODE_ERRORED) or MODE_ALLOWED to unrestrict.
1853     * @param exceptionPackages Optional list of packages to exclude from the restriction.
1854     * @hide
1855     */
1856    @RequiresPermission(android.Manifest.permission.MANAGE_APP_OPS_MODES)
1857    public void setRestriction(int code, @AttributeUsage int usage, int mode,
1858            String[] exceptionPackages) {
1859        try {
1860            final int uid = Binder.getCallingUid();
1861            mService.setAudioRestriction(code, usage, uid, mode, exceptionPackages);
1862        } catch (RemoteException e) {
1863            throw e.rethrowFromSystemServer();
1864        }
1865    }
1866
1867    /** @hide */
1868    @RequiresPermission(android.Manifest.permission.MANAGE_APP_OPS_MODES)
1869    public void resetAllModes() {
1870        try {
1871            mService.resetAllModes(mContext.getUserId(), null);
1872        } catch (RemoteException e) {
1873            throw e.rethrowFromSystemServer();
1874        }
1875    }
1876
1877    /**
1878     * Gets the app op name associated with a given permission.
1879     * The app op name is one of the public constants defined
1880     * in this class such as {@link #OPSTR_COARSE_LOCATION}.
1881     * This API is intended to be used for mapping runtime
1882     * permissions to the corresponding app op.
1883     *
1884     * @param permission The permission.
1885     * @return The app op associated with the permission or null.
1886     */
1887    public static String permissionToOp(String permission) {
1888        final Integer opCode = sPermToOp.get(permission);
1889        if (opCode == null) {
1890            return null;
1891        }
1892        return sOpToString[opCode];
1893    }
1894
1895    /**
1896     * Monitor for changes to the operating mode for the given op in the given app package.
1897     * You can watch op changes only for your UID.
1898     *
1899     * @param op The operation to monitor, one of OPSTR_*.
1900     * @param packageName The name of the application to monitor.
1901     * @param callback Where to report changes.
1902     */
1903    public void startWatchingMode(String op, String packageName,
1904            final OnOpChangedListener callback) {
1905        startWatchingMode(strOpToOp(op), packageName, callback);
1906    }
1907
1908    /**
1909     * Monitor for changes to the operating mode for the given op in the given app package.
1910     * You can watch op changes only for your UID.
1911     *
1912     * @param op The operation to monitor, one of OPSTR_*.
1913     * @param packageName The name of the application to monitor.
1914     * @param flags Option flags: any combination of {@link #WATCH_FOREGROUND_CHANGES} or 0.
1915     * @param callback Where to report changes.
1916     * @hide
1917     */
1918    public void startWatchingMode(String op, String packageName, int flags,
1919            final OnOpChangedListener callback) {
1920        startWatchingMode(strOpToOp(op), packageName, flags, callback);
1921    }
1922
1923    /**
1924     * Monitor for changes to the operating mode for the given op in the given app package.
1925     *
1926     * <p> If you don't hold the {@link android.Manifest.permission#WATCH_APPOPS} permission
1927     * you can watch changes only for your UID.
1928     *
1929     * @param op The operation to monitor, one of OP_*.
1930     * @param packageName The name of the application to monitor.
1931     * @param callback Where to report changes.
1932     * @hide
1933     */
1934    @RequiresPermission(value=android.Manifest.permission.WATCH_APPOPS, conditional=true)
1935    public void startWatchingMode(int op, String packageName, final OnOpChangedListener callback) {
1936        startWatchingMode(op, packageName, 0, callback);
1937    }
1938
1939    /**
1940     * Monitor for changes to the operating mode for the given op in the given app package.
1941     *
1942     * <p> If you don't hold the {@link android.Manifest.permission#WATCH_APPOPS} permission
1943     * you can watch changes only for your UID.
1944     *
1945     * @param op The operation to monitor, one of OP_*.
1946     * @param packageName The name of the application to monitor.
1947     * @param flags Option flags: any combination of {@link #WATCH_FOREGROUND_CHANGES} or 0.
1948     * @param callback Where to report changes.
1949     * @hide
1950     */
1951    @RequiresPermission(value=android.Manifest.permission.WATCH_APPOPS, conditional=true)
1952    public void startWatchingMode(int op, String packageName, int flags,
1953            final OnOpChangedListener callback) {
1954        synchronized (mModeWatchers) {
1955            IAppOpsCallback cb = mModeWatchers.get(callback);
1956            if (cb == null) {
1957                cb = new IAppOpsCallback.Stub() {
1958                    public void opChanged(int op, int uid, String packageName) {
1959                        if (callback instanceof OnOpChangedInternalListener) {
1960                            ((OnOpChangedInternalListener)callback).onOpChanged(op, packageName);
1961                        }
1962                        if (sOpToString[op] != null) {
1963                            callback.onOpChanged(sOpToString[op], packageName);
1964                        }
1965                    }
1966                };
1967                mModeWatchers.put(callback, cb);
1968            }
1969            try {
1970                mService.startWatchingModeWithFlags(op, packageName, flags, cb);
1971            } catch (RemoteException e) {
1972                throw e.rethrowFromSystemServer();
1973            }
1974        }
1975    }
1976
1977    /**
1978     * Stop monitoring that was previously started with {@link #startWatchingMode}.  All
1979     * monitoring associated with this callback will be removed.
1980     */
1981    public void stopWatchingMode(OnOpChangedListener callback) {
1982        synchronized (mModeWatchers) {
1983            IAppOpsCallback cb = mModeWatchers.get(callback);
1984            if (cb != null) {
1985                try {
1986                    mService.stopWatchingMode(cb);
1987                } catch (RemoteException e) {
1988                    throw e.rethrowFromSystemServer();
1989                }
1990            }
1991        }
1992    }
1993
1994    /**
1995     * Start watching for changes to the active state of app ops. An app op may be
1996     * long running and it has a clear start and stop delimiters. If an op is being
1997     * started or stopped by any package you will get a callback. To change the
1998     * watched ops for a registered callback you need to unregister and register it
1999     * again.
2000     *
2001     * <p> If you don't hold the {@link android.Manifest.permission#WATCH_APPOPS} permission
2002     * you can watch changes only for your UID.
2003     *
2004     * @param ops The ops to watch.
2005     * @param callback Where to report changes.
2006     *
2007     * @see #isOperationActive(int, int, String)
2008     * @see #stopWatchingActive(OnOpActiveChangedListener)
2009     * @see #startOp(int, int, String)
2010     * @see #finishOp(int, int, String)
2011     *
2012     * @hide
2013     */
2014    @TestApi
2015    // TODO: Uncomment below annotation once b/73559440 is fixed
2016    // @RequiresPermission(value=Manifest.permission.WATCH_APPOPS, conditional=true)
2017    public void startWatchingActive(@NonNull int[] ops,
2018            @NonNull OnOpActiveChangedListener callback) {
2019        Preconditions.checkNotNull(ops, "ops cannot be null");
2020        Preconditions.checkNotNull(callback, "callback cannot be null");
2021        IAppOpsActiveCallback cb;
2022        synchronized (mActiveWatchers) {
2023            cb = mActiveWatchers.get(callback);
2024            if (cb != null) {
2025                return;
2026            }
2027            cb = new IAppOpsActiveCallback.Stub() {
2028                @Override
2029                public void opActiveChanged(int op, int uid, String packageName, boolean active) {
2030                    callback.onOpActiveChanged(op, uid, packageName, active);
2031                }
2032            };
2033            mActiveWatchers.put(callback, cb);
2034        }
2035        try {
2036            mService.startWatchingActive(ops, cb);
2037        } catch (RemoteException e) {
2038            throw e.rethrowFromSystemServer();
2039        }
2040    }
2041
2042    /**
2043     * Stop watching for changes to the active state of an app op. An app op may be
2044     * long running and it has a clear start and stop delimiters. Unregistering a
2045     * non-registered callback has no effect.
2046     *
2047     * @see #isOperationActive#(int, int, String)
2048     * @see #startWatchingActive(int[], OnOpActiveChangedListener)
2049     * @see #startOp(int, int, String)
2050     * @see #finishOp(int, int, String)
2051     *
2052     * @hide
2053     */
2054    @TestApi
2055    public void stopWatchingActive(@NonNull OnOpActiveChangedListener callback) {
2056        synchronized (mActiveWatchers) {
2057            final IAppOpsActiveCallback cb = mActiveWatchers.get(callback);
2058            if (cb != null) {
2059                try {
2060                    mService.stopWatchingActive(cb);
2061                } catch (RemoteException e) {
2062                    throw e.rethrowFromSystemServer();
2063                }
2064            }
2065        }
2066    }
2067
2068    private String buildSecurityExceptionMsg(int op, int uid, String packageName) {
2069        return packageName + " from uid " + uid + " not allowed to perform " + sOpNames[op];
2070    }
2071
2072    /**
2073     * {@hide}
2074     */
2075    public static int strOpToOp(String op) {
2076        Integer val = sOpStrToOp.get(op);
2077        if (val == null) {
2078            throw new IllegalArgumentException("Unknown operation string: " + op);
2079        }
2080        return val;
2081    }
2082
2083    /**
2084     * Do a quick check for whether an application might be able to perform an operation.
2085     * This is <em>not</em> a security check; you must use {@link #noteOp(String, int, String)}
2086     * or {@link #startOp(String, int, String)} for your actual security checks, which also
2087     * ensure that the given uid and package name are consistent.  This function can just be
2088     * used for a quick check to see if an operation has been disabled for the application,
2089     * as an early reject of some work.  This does not modify the time stamp or other data
2090     * about the operation.
2091     *
2092     * <p>Important things this will not do (which you need to ultimate use
2093     * {@link #noteOp(String, int, String)} or {@link #startOp(String, int, String)} to cover):</p>
2094     * <ul>
2095     *     <li>Verifying the uid and package are consistent, so callers can't spoof
2096     *     their identity.</li>
2097     *     <li>Taking into account the current foreground/background state of the
2098     *     app; apps whose mode varies by this state will always be reported
2099     *     as {@link #MODE_ALLOWED}.</li>
2100     * </ul>
2101     *
2102     * @param op The operation to check.  One of the OPSTR_* constants.
2103     * @param uid The user id of the application attempting to perform the operation.
2104     * @param packageName The name of the application attempting to perform the operation.
2105     * @return Returns {@link #MODE_ALLOWED} if the operation is allowed, or
2106     * {@link #MODE_IGNORED} if it is not allowed and should be silently ignored (without
2107     * causing the app to crash).
2108     * @throws SecurityException If the app has been configured to crash on this op.
2109     */
2110    public int checkOp(String op, int uid, String packageName) {
2111        return checkOp(strOpToOp(op), uid, packageName);
2112    }
2113
2114    /**
2115     * Like {@link #checkOp} but instead of throwing a {@link SecurityException} it
2116     * returns {@link #MODE_ERRORED}.
2117     */
2118    public int checkOpNoThrow(String op, int uid, String packageName) {
2119        return checkOpNoThrow(strOpToOp(op), uid, packageName);
2120    }
2121
2122    /**
2123     * Like {@link #checkOp} but returns the <em>raw</em> mode associated with the op.
2124     * Does not throw a security exception, does not translate {@link #MODE_FOREGROUND}.
2125     * @hide
2126     */
2127    public int unsafeCheckOpRaw(String op, int uid, String packageName) {
2128        try {
2129            return mService.checkOperation(strOpToOp(op), uid, packageName);
2130        } catch (RemoteException e) {
2131            throw e.rethrowFromSystemServer();
2132        }
2133    }
2134
2135    /**
2136     * Make note of an application performing an operation.  Note that you must pass
2137     * in both the uid and name of the application to be checked; this function will verify
2138     * that these two match, and if not, return {@link #MODE_IGNORED}.  If this call
2139     * succeeds, the last execution time of the operation for this app will be updated to
2140     * the current time.
2141     * @param op The operation to note.  One of the OPSTR_* constants.
2142     * @param uid The user id of the application attempting to perform the operation.
2143     * @param packageName The name of the application attempting to perform the operation.
2144     * @return Returns {@link #MODE_ALLOWED} if the operation is allowed, or
2145     * {@link #MODE_IGNORED} if it is not allowed and should be silently ignored (without
2146     * causing the app to crash).
2147     * @throws SecurityException If the app has been configured to crash on this op.
2148     */
2149    public int noteOp(String op, int uid, String packageName) {
2150        return noteOp(strOpToOp(op), uid, packageName);
2151    }
2152
2153    /**
2154     * Like {@link #noteOp} but instead of throwing a {@link SecurityException} it
2155     * returns {@link #MODE_ERRORED}.
2156     */
2157    public int noteOpNoThrow(String op, int uid, String packageName) {
2158        return noteOpNoThrow(strOpToOp(op), uid, packageName);
2159    }
2160
2161    /**
2162     * Make note of an application performing an operation on behalf of another
2163     * application when handling an IPC. Note that you must pass the package name
2164     * of the application that is being proxied while its UID will be inferred from
2165     * the IPC state; this function will verify that the calling uid and proxied
2166     * package name match, and if not, return {@link #MODE_IGNORED}. If this call
2167     * succeeds, the last execution time of the operation for the proxied app and
2168     * your app will be updated to the current time.
2169     * @param op The operation to note.  One of the OPSTR_* constants.
2170     * @param proxiedPackageName The name of the application calling into the proxy application.
2171     * @return Returns {@link #MODE_ALLOWED} if the operation is allowed, or
2172     * {@link #MODE_IGNORED} if it is not allowed and should be silently ignored (without
2173     * causing the app to crash).
2174     * @throws SecurityException If the app has been configured to crash on this op.
2175     */
2176    public int noteProxyOp(String op, String proxiedPackageName) {
2177        return noteProxyOp(strOpToOp(op), proxiedPackageName);
2178    }
2179
2180    /**
2181     * Like {@link #noteProxyOp(String, String)} but instead
2182     * of throwing a {@link SecurityException} it returns {@link #MODE_ERRORED}.
2183     */
2184    public int noteProxyOpNoThrow(String op, String proxiedPackageName) {
2185        return noteProxyOpNoThrow(strOpToOp(op), proxiedPackageName);
2186    }
2187
2188    /**
2189     * Report that an application has started executing a long-running operation.  Note that you
2190     * must pass in both the uid and name of the application to be checked; this function will
2191     * verify that these two match, and if not, return {@link #MODE_IGNORED}.  If this call
2192     * succeeds, the last execution time of the operation for this app will be updated to
2193     * the current time and the operation will be marked as "running".  In this case you must
2194     * later call {@link #finishOp(String, int, String)} to report when the application is no
2195     * longer performing the operation.
2196     * @param op The operation to start.  One of the OPSTR_* constants.
2197     * @param uid The user id of the application attempting to perform the operation.
2198     * @param packageName The name of the application attempting to perform the operation.
2199     * @return Returns {@link #MODE_ALLOWED} if the operation is allowed, or
2200     * {@link #MODE_IGNORED} if it is not allowed and should be silently ignored (without
2201     * causing the app to crash).
2202     * @throws SecurityException If the app has been configured to crash on this op.
2203     */
2204    public int startOp(String op, int uid, String packageName) {
2205        return startOp(strOpToOp(op), uid, packageName);
2206    }
2207
2208    /**
2209     * Like {@link #startOp} but instead of throwing a {@link SecurityException} it
2210     * returns {@link #MODE_ERRORED}.
2211     */
2212    public int startOpNoThrow(String op, int uid, String packageName) {
2213        return startOpNoThrow(strOpToOp(op), uid, packageName);
2214    }
2215
2216    /**
2217     * Report that an application is no longer performing an operation that had previously
2218     * been started with {@link #startOp(String, int, String)}.  There is no validation of input
2219     * or result; the parameters supplied here must be the exact same ones previously passed
2220     * in when starting the operation.
2221     */
2222    public void finishOp(String op, int uid, String packageName) {
2223        finishOp(strOpToOp(op), uid, packageName);
2224    }
2225
2226    /**
2227     * Do a quick check for whether an application might be able to perform an operation.
2228     * This is <em>not</em> a security check; you must use {@link #noteOp(int, int, String)}
2229     * or {@link #startOp(int, int, String)} for your actual security checks, which also
2230     * ensure that the given uid and package name are consistent.  This function can just be
2231     * used for a quick check to see if an operation has been disabled for the application,
2232     * as an early reject of some work.  This does not modify the time stamp or other data
2233     * about the operation.
2234     *
2235     * <p>Important things this will not do (which you need to ultimate use
2236     * {@link #noteOp(int, int, String)} or {@link #startOp(int, int, String)} to cover):</p>
2237     * <ul>
2238     *     <li>Verifying the uid and package are consistent, so callers can't spoof
2239     *     their identity.</li>
2240     *     <li>Taking into account the current foreground/background state of the
2241     *     app; apps whose mode varies by this state will always be reported
2242     *     as {@link #MODE_ALLOWED}.</li>
2243     * </ul>
2244     *
2245     * @param op The operation to check.  One of the OP_* constants.
2246     * @param uid The user id of the application attempting to perform the operation.
2247     * @param packageName The name of the application attempting to perform the operation.
2248     * @return Returns {@link #MODE_ALLOWED} if the operation is allowed, or
2249     * {@link #MODE_IGNORED} if it is not allowed and should be silently ignored (without
2250     * causing the app to crash).
2251     * @throws SecurityException If the app has been configured to crash on this op.
2252     * @hide
2253     */
2254    public int checkOp(int op, int uid, String packageName) {
2255        try {
2256            int mode = mService.checkOperation(op, uid, packageName);
2257            if (mode == MODE_ERRORED) {
2258                throw new SecurityException(buildSecurityExceptionMsg(op, uid, packageName));
2259            }
2260            return mode;
2261        } catch (RemoteException e) {
2262            throw e.rethrowFromSystemServer();
2263        }
2264    }
2265
2266    /**
2267     * Like {@link #checkOp} but instead of throwing a {@link SecurityException} it
2268     * returns {@link #MODE_ERRORED}.
2269     * @hide
2270     */
2271    public int checkOpNoThrow(int op, int uid, String packageName) {
2272        try {
2273            int mode = mService.checkOperation(op, uid, packageName);
2274            return mode == AppOpsManager.MODE_FOREGROUND ? AppOpsManager.MODE_ALLOWED : mode;
2275        } catch (RemoteException e) {
2276            throw e.rethrowFromSystemServer();
2277        }
2278    }
2279
2280    /**
2281     * Do a quick check to validate if a package name belongs to a UID.
2282     *
2283     * @throws SecurityException if the package name doesn't belong to the given
2284     *             UID, or if ownership cannot be verified.
2285     */
2286    public void checkPackage(int uid, String packageName) {
2287        try {
2288            if (mService.checkPackage(uid, packageName) != MODE_ALLOWED) {
2289                throw new SecurityException(
2290                        "Package " + packageName + " does not belong to " + uid);
2291            }
2292        } catch (RemoteException e) {
2293            throw e.rethrowFromSystemServer();
2294        }
2295    }
2296
2297    /**
2298     * Like {@link #checkOp} but at a stream-level for audio operations.
2299     * @hide
2300     */
2301    public int checkAudioOp(int op, int stream, int uid, String packageName) {
2302        try {
2303            final int mode = mService.checkAudioOperation(op, stream, uid, packageName);
2304            if (mode == MODE_ERRORED) {
2305                throw new SecurityException(buildSecurityExceptionMsg(op, uid, packageName));
2306            }
2307            return mode;
2308        } catch (RemoteException e) {
2309            throw e.rethrowFromSystemServer();
2310        }
2311    }
2312
2313    /**
2314     * Like {@link #checkAudioOp} but instead of throwing a {@link SecurityException} it
2315     * returns {@link #MODE_ERRORED}.
2316     * @hide
2317     */
2318    public int checkAudioOpNoThrow(int op, int stream, int uid, String packageName) {
2319        try {
2320            return mService.checkAudioOperation(op, stream, uid, packageName);
2321        } catch (RemoteException e) {
2322            throw e.rethrowFromSystemServer();
2323        }
2324    }
2325
2326    /**
2327     * Make note of an application performing an operation.  Note that you must pass
2328     * in both the uid and name of the application to be checked; this function will verify
2329     * that these two match, and if not, return {@link #MODE_IGNORED}.  If this call
2330     * succeeds, the last execution time of the operation for this app will be updated to
2331     * the current time.
2332     * @param op The operation to note.  One of the OP_* constants.
2333     * @param uid The user id of the application attempting to perform the operation.
2334     * @param packageName The name of the application attempting to perform the operation.
2335     * @return Returns {@link #MODE_ALLOWED} if the operation is allowed, or
2336     * {@link #MODE_IGNORED} if it is not allowed and should be silently ignored (without
2337     * causing the app to crash).
2338     * @throws SecurityException If the app has been configured to crash on this op.
2339     * @hide
2340     */
2341    public int noteOp(int op, int uid, String packageName) {
2342        final int mode = noteOpNoThrow(op, uid, packageName);
2343        if (mode == MODE_ERRORED) {
2344            throw new SecurityException(buildSecurityExceptionMsg(op, uid, packageName));
2345        }
2346        return mode;
2347    }
2348
2349    /**
2350     * Make note of an application performing an operation on behalf of another
2351     * application when handling an IPC. Note that you must pass the package name
2352     * of the application that is being proxied while its UID will be inferred from
2353     * the IPC state; this function will verify that the calling uid and proxied
2354     * package name match, and if not, return {@link #MODE_IGNORED}. If this call
2355     * succeeds, the last execution time of the operation for the proxied app and
2356     * your app will be updated to the current time.
2357     * @param op The operation to note. One of the OPSTR_* constants.
2358     * @param proxiedPackageName The name of the application calling into the proxy application.
2359     * @return Returns {@link #MODE_ALLOWED} if the operation is allowed, or
2360     * {@link #MODE_IGNORED} if it is not allowed and should be silently ignored (without
2361     * causing the app to crash).
2362     * @throws SecurityException If the proxy or proxied app has been configured to
2363     * crash on this op.
2364     *
2365     * @hide
2366     */
2367    public int noteProxyOp(int op, String proxiedPackageName) {
2368        int mode = noteProxyOpNoThrow(op, proxiedPackageName);
2369        if (mode == MODE_ERRORED) {
2370            throw new SecurityException("Proxy package " + mContext.getOpPackageName()
2371                    + " from uid " + Process.myUid() + " or calling package "
2372                    + proxiedPackageName + " from uid " + Binder.getCallingUid()
2373                    + " not allowed to perform " + sOpNames[op]);
2374        }
2375        return mode;
2376    }
2377
2378    /**
2379     * Like {@link #noteProxyOp(int, String)} but instead
2380     * of throwing a {@link SecurityException} it returns {@link #MODE_ERRORED}.
2381     * @hide
2382     */
2383    public int noteProxyOpNoThrow(int op, String proxiedPackageName) {
2384        try {
2385            return mService.noteProxyOperation(op, mContext.getOpPackageName(),
2386                    Binder.getCallingUid(), proxiedPackageName);
2387        } catch (RemoteException e) {
2388            throw e.rethrowFromSystemServer();
2389        }
2390    }
2391
2392    /**
2393     * Like {@link #noteOp} but instead of throwing a {@link SecurityException} it
2394     * returns {@link #MODE_ERRORED}.
2395     * @hide
2396     */
2397    public int noteOpNoThrow(int op, int uid, String packageName) {
2398        try {
2399            return mService.noteOperation(op, uid, packageName);
2400        } catch (RemoteException e) {
2401            throw e.rethrowFromSystemServer();
2402        }
2403    }
2404
2405    /** @hide */
2406    public int noteOp(int op) {
2407        return noteOp(op, Process.myUid(), mContext.getOpPackageName());
2408    }
2409
2410    /** @hide */
2411    public static IBinder getToken(IAppOpsService service) {
2412        synchronized (AppOpsManager.class) {
2413            if (sToken != null) {
2414                return sToken;
2415            }
2416            try {
2417                sToken = service.getToken(new Binder());
2418            } catch (RemoteException e) {
2419                throw e.rethrowFromSystemServer();
2420            }
2421            return sToken;
2422        }
2423    }
2424
2425    /** @hide */
2426    public int startOp(int op) {
2427        return startOp(op, Process.myUid(), mContext.getOpPackageName());
2428    }
2429
2430    /**
2431     * Report that an application has started executing a long-running operation.  Note that you
2432     * must pass in both the uid and name of the application to be checked; this function will
2433     * verify that these two match, and if not, return {@link #MODE_IGNORED}.  If this call
2434     * succeeds, the last execution time of the operation for this app will be updated to
2435     * the current time and the operation will be marked as "running".  In this case you must
2436     * later call {@link #finishOp(int, int, String)} to report when the application is no
2437     * longer performing the operation.
2438     *
2439     * @param op The operation to start.  One of the OP_* constants.
2440     * @param uid The user id of the application attempting to perform the operation.
2441     * @param packageName The name of the application attempting to perform the operation.
2442     * @return Returns {@link #MODE_ALLOWED} if the operation is allowed, or
2443     * {@link #MODE_IGNORED} if it is not allowed and should be silently ignored (without
2444     * causing the app to crash).
2445     * @throws SecurityException If the app has been configured to crash on this op.
2446     * @hide
2447     */
2448    public int startOp(int op, int uid, String packageName) {
2449        return startOp(op, uid, packageName, false);
2450    }
2451
2452    /**
2453     * Report that an application has started executing a long-running operation. Similar
2454     * to {@link #startOp(String, int, String) except that if the mode is {@link #MODE_DEFAULT}
2455     * the operation should succeed since the caller has performed its standard permission
2456     * checks which passed and would perform the protected operation for this mode.
2457     *
2458     * @param op The operation to start.  One of the OP_* constants.
2459     * @param uid The user id of the application attempting to perform the operation.
2460     * @param packageName The name of the application attempting to perform the operation.
2461     * @return Returns {@link #MODE_ALLOWED} if the operation is allowed, or
2462     * {@link #MODE_IGNORED} if it is not allowed and should be silently ignored (without
2463     * causing the app to crash).
2464     * @param startIfModeDefault Whether to start if mode is {@link #MODE_DEFAULT}.
2465     *
2466     * @throws SecurityException If the app has been configured to crash on this op or
2467     * the package is not in the passed in UID.
2468     *
2469     * @hide
2470     */
2471    public int startOp(int op, int uid, String packageName, boolean startIfModeDefault) {
2472        final int mode = startOpNoThrow(op, uid, packageName, startIfModeDefault);
2473        if (mode == MODE_ERRORED) {
2474            throw new SecurityException(buildSecurityExceptionMsg(op, uid, packageName));
2475        }
2476        return mode;
2477    }
2478
2479    /**
2480     * Like {@link #startOp} but instead of throwing a {@link SecurityException} it
2481     * returns {@link #MODE_ERRORED}.
2482     * @hide
2483     */
2484    public int startOpNoThrow(int op, int uid, String packageName) {
2485        return startOpNoThrow(op, uid, packageName, false);
2486    }
2487
2488    /**
2489     * Like {@link #startOp(int, int, String, boolean)} but instead of throwing a
2490     * {@link SecurityException} it returns {@link #MODE_ERRORED}.
2491     *
2492     * @param op The operation to start.  One of the OP_* constants.
2493     * @param uid The user id of the application attempting to perform the operation.
2494     * @param packageName The name of the application attempting to perform the operation.
2495     * @return Returns {@link #MODE_ALLOWED} if the operation is allowed, or
2496     * {@link #MODE_IGNORED} if it is not allowed and should be silently ignored (without
2497     * causing the app to crash).
2498     * @param startIfModeDefault Whether to start if mode is {@link #MODE_DEFAULT}.
2499     *
2500     * @hide
2501     */
2502    public int startOpNoThrow(int op, int uid, String packageName, boolean startIfModeDefault) {
2503        try {
2504            return mService.startOperation(getToken(mService), op, uid, packageName,
2505                    startIfModeDefault);
2506        } catch (RemoteException e) {
2507            throw e.rethrowFromSystemServer();
2508        }
2509    }
2510
2511    /**
2512     * Report that an application is no longer performing an operation that had previously
2513     * been started with {@link #startOp(int, int, String)}.  There is no validation of input
2514     * or result; the parameters supplied here must be the exact same ones previously passed
2515     * in when starting the operation.
2516     * @hide
2517     */
2518    public void finishOp(int op, int uid, String packageName) {
2519        try {
2520            mService.finishOperation(getToken(mService), op, uid, packageName);
2521        } catch (RemoteException e) {
2522            throw e.rethrowFromSystemServer();
2523        }
2524    }
2525
2526    /** @hide */
2527    public void finishOp(int op) {
2528        finishOp(op, Process.myUid(), mContext.getOpPackageName());
2529    }
2530
2531    /**
2532     * Checks whether the given op for a UID and package is active.
2533     *
2534     * <p> If you don't hold the {@link android.Manifest.permission#WATCH_APPOPS} permission
2535     * you can query only for your UID.
2536     *
2537     * @see #startWatchingActive(int[], OnOpActiveChangedListener)
2538     * @see #stopWatchingMode(OnOpChangedListener)
2539     * @see #finishOp(int)
2540     * @see #startOp(int)
2541     *
2542     * @hide */
2543    @TestApi
2544    // TODO: Uncomment below annotation once b/73559440 is fixed
2545    // @RequiresPermission(value=Manifest.permission.WATCH_APPOPS, conditional=true)
2546    public boolean isOperationActive(int code, int uid, String packageName) {
2547        try {
2548            return mService.isOperationActive(code, uid, packageName);
2549        } catch (RemoteException e) {
2550            throw e.rethrowFromSystemServer();
2551        }
2552    }
2553
2554    /**
2555     * Returns all supported operation names.
2556     * @hide
2557     */
2558    @SystemApi
2559    @TestApi
2560    public static String[] getOpStrs() {
2561        return Arrays.copyOf(sOpToString, sOpToString.length);
2562    }
2563
2564    /**
2565     * @hide
2566     */
2567    public static long maxTime(long[] times, int start, int end) {
2568        long time = 0;
2569        for (int i = start; i < end; i++) {
2570            if (times[i] > time) {
2571                time = times[i];
2572            }
2573        }
2574        return time;
2575    }
2576}
2577