OSDN Git Service

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