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