1 /* 2 * Copyright (C) 2017 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 com.android.server.cts.device.statsdatom; 18 19 import static com.android.compatibility.common.util.SystemUtil.runShellCommand; 20 21 import static com.google.common.truth.Truth.assertWithMessage; 22 23 import static org.junit.Assert.assertNotNull; 24 import static org.junit.Assume.assumeNotNull; 25 import static org.junit.Assume.assumeTrue; 26 27 import android.accounts.Account; 28 import android.accounts.AccountManager; 29 import android.app.ActivityManager; 30 import android.app.ActivityManager.RunningServiceInfo; 31 import android.app.AppOpsManager; 32 import android.app.GameManager; 33 import android.app.GameModeConfiguration; 34 import android.app.GameState; 35 import android.app.job.JobInfo; 36 import android.app.job.JobScheduler; 37 import android.app.usage.NetworkStatsManager; 38 import android.bluetooth.BluetoothAdapter; 39 import android.bluetooth.le.BluetoothLeScanner; 40 import android.bluetooth.le.ScanCallback; 41 import android.bluetooth.le.ScanFilter; 42 import android.bluetooth.le.ScanResult; 43 import android.bluetooth.le.ScanSettings; 44 import android.content.BroadcastReceiver; 45 import android.content.ComponentName; 46 import android.content.ContentResolver; 47 import android.content.Context; 48 import android.content.Intent; 49 import android.content.IntentFilter; 50 import android.content.pm.ApplicationInfo; 51 import android.hardware.camera2.CameraCharacteristics; 52 import android.hardware.camera2.CameraDevice; 53 import android.hardware.camera2.CameraManager; 54 import android.location.GnssStatus; 55 import android.location.Location; 56 import android.location.LocationListener; 57 import android.location.LocationManager; 58 import android.media.MediaDrm; 59 import android.media.MediaPlayer; 60 import android.net.ConnectivityManager; 61 import android.net.Network; 62 import android.net.NetworkCapabilities; 63 import android.net.NetworkRequest; 64 import android.net.cts.util.CtsNetUtils; 65 import android.net.wifi.WifiManager; 66 import android.os.AsyncTask; 67 import android.os.Build; 68 import android.os.Bundle; 69 import android.os.Handler; 70 import android.os.HandlerThread; 71 import android.os.Looper; 72 import android.os.PerformanceHintManager; 73 import android.os.PowerManager; 74 import android.os.Process; 75 import android.os.RemoteException; 76 import android.os.SystemClock; 77 import android.os.VibrationEffect; 78 import android.os.Vibrator; 79 import android.provider.Settings; 80 import android.text.TextUtils; 81 import android.util.ArrayMap; 82 import android.util.Log; 83 import android.util.StatsEvent; 84 import android.util.StatsLog; 85 86 import androidx.annotation.NonNull; 87 import androidx.test.InstrumentationRegistry; 88 89 import com.android.compatibility.common.util.PollingCheck; 90 import com.android.compatibility.common.util.PropertyUtil; 91 import com.android.compatibility.common.util.ShellIdentityUtils; 92 93 import libcore.javax.net.ssl.TestSSLContext; 94 import libcore.javax.net.ssl.TestSSLSocketPair; 95 96 import org.junit.Assert; 97 import org.junit.Test; 98 99 import java.net.HttpURLConnection; 100 import java.net.URL; 101 import java.util.Arrays; 102 import java.util.List; 103 import java.util.Map; 104 import java.util.UUID; 105 import java.util.concurrent.CountDownLatch; 106 import java.util.concurrent.TimeUnit; 107 import java.util.function.BiConsumer; 108 109 import javax.net.ssl.SSLSocket; 110 111 public class AtomTests { 112 private static final String TAG = AtomTests.class.getSimpleName(); 113 114 private static final String MY_PACKAGE_NAME = "com.android.server.cts.device.statsdatom"; 115 116 private static final Map<String, Integer> APP_OPS_ENUM_MAP = new ArrayMap<>(); 117 118 static { APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_COARSE_LOCATION, 0)119 APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_COARSE_LOCATION, 0); APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_FINE_LOCATION, 1)120 APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_FINE_LOCATION, 1); APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_GPS, 2)121 APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_GPS, 2); APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_VIBRATE, 3)122 APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_VIBRATE, 3); APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_READ_CONTACTS, 4)123 APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_READ_CONTACTS, 4); APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_WRITE_CONTACTS, 5)124 APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_WRITE_CONTACTS, 5); APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_READ_CALL_LOG, 6)125 APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_READ_CALL_LOG, 6); APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_WRITE_CALL_LOG, 7)126 APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_WRITE_CALL_LOG, 7); APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_READ_CALENDAR, 8)127 APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_READ_CALENDAR, 8); APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_WRITE_CALENDAR, 9)128 APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_WRITE_CALENDAR, 9); APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_WIFI_SCAN, 10)129 APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_WIFI_SCAN, 10); APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_POST_NOTIFICATION, 11)130 APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_POST_NOTIFICATION, 11); APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_NEIGHBORING_CELLS, 12)131 APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_NEIGHBORING_CELLS, 12); APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_CALL_PHONE, 13)132 APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_CALL_PHONE, 13); APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_READ_SMS, 14)133 APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_READ_SMS, 14); APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_WRITE_SMS, 15)134 APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_WRITE_SMS, 15); APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_RECEIVE_SMS, 16)135 APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_RECEIVE_SMS, 16); APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_RECEIVE_EMERGENCY_BROADCAST, 17)136 APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_RECEIVE_EMERGENCY_BROADCAST, 17); APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_RECEIVE_MMS, 18)137 APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_RECEIVE_MMS, 18); APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_RECEIVE_WAP_PUSH, 19)138 APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_RECEIVE_WAP_PUSH, 19); APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_SEND_SMS, 20)139 APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_SEND_SMS, 20); APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_READ_ICC_SMS, 21)140 APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_READ_ICC_SMS, 21); APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_WRITE_ICC_SMS, 22)141 APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_WRITE_ICC_SMS, 22); APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_WRITE_SETTINGS, 23)142 APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_WRITE_SETTINGS, 23); APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_SYSTEM_ALERT_WINDOW, 24)143 APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_SYSTEM_ALERT_WINDOW, 24); APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_ACCESS_NOTIFICATIONS, 25)144 APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_ACCESS_NOTIFICATIONS, 25); APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_CAMERA, 26)145 APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_CAMERA, 26); APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_RECORD_AUDIO, 27)146 APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_RECORD_AUDIO, 27); APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_PLAY_AUDIO, 28)147 APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_PLAY_AUDIO, 28); APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_READ_CLIPBOARD, 29)148 APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_READ_CLIPBOARD, 29); APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_WRITE_CLIPBOARD, 30)149 APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_WRITE_CLIPBOARD, 30); APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_TAKE_MEDIA_BUTTONS, 31)150 APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_TAKE_MEDIA_BUTTONS, 31); APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_TAKE_AUDIO_FOCUS, 32)151 APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_TAKE_AUDIO_FOCUS, 32); APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_AUDIO_MASTER_VOLUME, 33)152 APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_AUDIO_MASTER_VOLUME, 33); APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_AUDIO_VOICE_VOLUME, 34)153 APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_AUDIO_VOICE_VOLUME, 34); APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_AUDIO_RING_VOLUME, 35)154 APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_AUDIO_RING_VOLUME, 35); APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_AUDIO_MEDIA_VOLUME, 36)155 APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_AUDIO_MEDIA_VOLUME, 36); APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_AUDIO_ALARM_VOLUME, 37)156 APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_AUDIO_ALARM_VOLUME, 37); APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_AUDIO_NOTIFICATION_VOLUME, 38)157 APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_AUDIO_NOTIFICATION_VOLUME, 38); APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_AUDIO_BLUETOOTH_VOLUME, 39)158 APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_AUDIO_BLUETOOTH_VOLUME, 39); APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_WAKE_LOCK, 40)159 APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_WAKE_LOCK, 40); APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_MONITOR_LOCATION, 41)160 APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_MONITOR_LOCATION, 41); APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_MONITOR_HIGH_POWER_LOCATION, 42)161 APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_MONITOR_HIGH_POWER_LOCATION, 42); APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_GET_USAGE_STATS, 43)162 APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_GET_USAGE_STATS, 43); APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_MUTE_MICROPHONE, 44)163 APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_MUTE_MICROPHONE, 44); APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_TOAST_WINDOW, 45)164 APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_TOAST_WINDOW, 45); APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_PROJECT_MEDIA, 46)165 APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_PROJECT_MEDIA, 46); APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_ACTIVATE_VPN, 47)166 APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_ACTIVATE_VPN, 47); APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_WRITE_WALLPAPER, 48)167 APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_WRITE_WALLPAPER, 48); APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_ASSIST_STRUCTURE, 49)168 APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_ASSIST_STRUCTURE, 49); APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_ASSIST_SCREENSHOT, 50)169 APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_ASSIST_SCREENSHOT, 50); APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_READ_PHONE_STATE, 51)170 APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_READ_PHONE_STATE, 51); APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_ADD_VOICEMAIL, 52)171 APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_ADD_VOICEMAIL, 52); APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_USE_SIP, 53)172 APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_USE_SIP, 53); APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_PROCESS_OUTGOING_CALLS, 54)173 APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_PROCESS_OUTGOING_CALLS, 54); APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_USE_FINGERPRINT, 55)174 APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_USE_FINGERPRINT, 55); APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_BODY_SENSORS, 56)175 APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_BODY_SENSORS, 56); APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_READ_CELL_BROADCASTS, 57)176 APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_READ_CELL_BROADCASTS, 57); APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_MOCK_LOCATION, 58)177 APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_MOCK_LOCATION, 58); APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_READ_EXTERNAL_STORAGE, 59)178 APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_READ_EXTERNAL_STORAGE, 59); APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_WRITE_EXTERNAL_STORAGE, 60)179 APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_WRITE_EXTERNAL_STORAGE, 60); APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_TURN_SCREEN_ON, 61)180 APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_TURN_SCREEN_ON, 61); APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_GET_ACCOUNTS, 62)181 APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_GET_ACCOUNTS, 62); APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_RUN_IN_BACKGROUND, 63)182 APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_RUN_IN_BACKGROUND, 63); APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_AUDIO_ACCESSIBILITY_VOLUME, 64)183 APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_AUDIO_ACCESSIBILITY_VOLUME, 64); APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_READ_PHONE_NUMBERS, 65)184 APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_READ_PHONE_NUMBERS, 65); APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_REQUEST_INSTALL_PACKAGES, 66)185 APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_REQUEST_INSTALL_PACKAGES, 66); APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_PICTURE_IN_PICTURE, 67)186 APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_PICTURE_IN_PICTURE, 67); APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_INSTANT_APP_START_FOREGROUND, 68)187 APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_INSTANT_APP_START_FOREGROUND, 68); APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_ANSWER_PHONE_CALLS, 69)188 APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_ANSWER_PHONE_CALLS, 69); APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_RUN_ANY_IN_BACKGROUND, 70)189 APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_RUN_ANY_IN_BACKGROUND, 70); APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_CHANGE_WIFI_STATE, 71)190 APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_CHANGE_WIFI_STATE, 71); APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_REQUEST_DELETE_PACKAGES, 72)191 APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_REQUEST_DELETE_PACKAGES, 72); APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_BIND_ACCESSIBILITY_SERVICE, 73)192 APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_BIND_ACCESSIBILITY_SERVICE, 73); APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_ACCEPT_HANDOVER, 74)193 APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_ACCEPT_HANDOVER, 74); APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_MANAGE_IPSEC_TUNNELS, 75)194 APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_MANAGE_IPSEC_TUNNELS, 75); APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_START_FOREGROUND, 76)195 APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_START_FOREGROUND, 76); APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_BLUETOOTH_SCAN, 77)196 APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_BLUETOOTH_SCAN, 77); APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_USE_BIOMETRIC, 78)197 APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_USE_BIOMETRIC, 78); APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_ACTIVITY_RECOGNITION, 79)198 APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_ACTIVITY_RECOGNITION, 79); APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_SMS_FINANCIAL_TRANSACTIONS, 80)199 APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_SMS_FINANCIAL_TRANSACTIONS, 80); APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_READ_MEDIA_AUDIO, 81)200 APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_READ_MEDIA_AUDIO, 81); APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_WRITE_MEDIA_AUDIO, 82)201 APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_WRITE_MEDIA_AUDIO, 82); APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_READ_MEDIA_VIDEO, 83)202 APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_READ_MEDIA_VIDEO, 83); APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_WRITE_MEDIA_VIDEO, 84)203 APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_WRITE_MEDIA_VIDEO, 84); APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_READ_MEDIA_IMAGES, 85)204 APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_READ_MEDIA_IMAGES, 85); APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_WRITE_MEDIA_IMAGES, 86)205 APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_WRITE_MEDIA_IMAGES, 86); APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_LEGACY_STORAGE, 87)206 APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_LEGACY_STORAGE, 87); APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_ACCESS_ACCESSIBILITY, 88)207 APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_ACCESS_ACCESSIBILITY, 88); APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_READ_DEVICE_IDENTIFIERS, 89)208 APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_READ_DEVICE_IDENTIFIERS, 89); APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_ACCESS_MEDIA_LOCATION, 90)209 APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_ACCESS_MEDIA_LOCATION, 90); APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_QUERY_ALL_PACKAGES, 91)210 APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_QUERY_ALL_PACKAGES, 91); APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_MANAGE_EXTERNAL_STORAGE, 92)211 APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_MANAGE_EXTERNAL_STORAGE, 92); APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_INTERACT_ACROSS_PROFILES, 93)212 APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_INTERACT_ACROSS_PROFILES, 93); APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_ACTIVATE_PLATFORM_VPN, 94)213 APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_ACTIVATE_PLATFORM_VPN, 94); APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_LOADER_USAGE_STATS, 95)214 APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_LOADER_USAGE_STATS, 95); 215 // Op 96 was deprecated/removed APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_AUTO_REVOKE_PERMISSIONS_IF_UNUSED, 97)216 APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_AUTO_REVOKE_PERMISSIONS_IF_UNUSED, 97); APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_AUTO_REVOKE_MANAGED_BY_INSTALLER, 98)217 APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_AUTO_REVOKE_MANAGED_BY_INSTALLER, 98); APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_NO_ISOLATED_STORAGE, 99)218 APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_NO_ISOLATED_STORAGE, 99); APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_PHONE_CALL_MICROPHONE, 100)219 APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_PHONE_CALL_MICROPHONE, 100); APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_PHONE_CALL_CAMERA, 101)220 APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_PHONE_CALL_CAMERA, 101); APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_RECORD_AUDIO_HOTWORD, 102)221 APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_RECORD_AUDIO_HOTWORD, 102); APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_MANAGE_ONGOING_CALLS, 103)222 APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_MANAGE_ONGOING_CALLS, 103); APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_MANAGE_CREDENTIALS, 104)223 APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_MANAGE_CREDENTIALS, 104); APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_USE_ICC_AUTH_WITH_DEVICE_IDENTIFIER, 105)224 APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_USE_ICC_AUTH_WITH_DEVICE_IDENTIFIER, 105); APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_RECORD_AUDIO_OUTPUT, 106)225 APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_RECORD_AUDIO_OUTPUT, 106); APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_SCHEDULE_EXACT_ALARM, 107)226 APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_SCHEDULE_EXACT_ALARM, 107); APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_FINE_LOCATION_SOURCE, 108)227 APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_FINE_LOCATION_SOURCE, 108); APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_COARSE_LOCATION_SOURCE, 109)228 APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_COARSE_LOCATION_SOURCE, 109); APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_MANAGE_MEDIA, 110)229 APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_MANAGE_MEDIA, 110); APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_BLUETOOTH_CONNECT, 111)230 APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_BLUETOOTH_CONNECT, 111); APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_UWB_RANGING, 112)231 APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_UWB_RANGING, 112); APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_ACTIVITY_RECOGNITION_SOURCE, 113)232 APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_ACTIVITY_RECOGNITION_SOURCE, 113); APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_BLUETOOTH_ADVERTISE, 114)233 APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_BLUETOOTH_ADVERTISE, 114); APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_RECORD_INCOMING_PHONE_AUDIO, 115)234 APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_RECORD_INCOMING_PHONE_AUDIO, 115); APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_NEARBY_WIFI_DEVICES, 116)235 APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_NEARBY_WIFI_DEVICES, 116); APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_ESTABLISH_VPN_SERVICE, 117)236 APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_ESTABLISH_VPN_SERVICE, 117); APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_ESTABLISH_VPN_MANAGER, 118)237 APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_ESTABLISH_VPN_MANAGER, 118); APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_ACCESS_RESTRICTED_SETTINGS, 119)238 APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_ACCESS_RESTRICTED_SETTINGS, 119); APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_RECEIVE_AMBIENT_TRIGGER_AUDIO, 120)239 APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_RECEIVE_AMBIENT_TRIGGER_AUDIO, 120); APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_RECEIVE_EXPLICIT_USER_INTERACTION_AUDIO, 121)240 APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_RECEIVE_EXPLICIT_USER_INTERACTION_AUDIO, 121); APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_RUN_USER_INITIATED_JOBS, 122)241 APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_RUN_USER_INITIATED_JOBS, 122); APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_READ_MEDIA_VISUAL_USER_SELECTED, 123)242 APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_READ_MEDIA_VISUAL_USER_SELECTED, 123); APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_SYSTEM_EXEMPT_FROM_SUSPENSION, 124)243 APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_SYSTEM_EXEMPT_FROM_SUSPENSION, 124); APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_SYSTEM_EXEMPT_FROM_DISMISSIBLE_NOTIFICATIONS, 125)244 APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_SYSTEM_EXEMPT_FROM_DISMISSIBLE_NOTIFICATIONS, 125); APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_READ_WRITE_HEALTH_DATA, 126)245 APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_READ_WRITE_HEALTH_DATA, 126); APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_FOREGROUND_SERVICE_SPECIAL_USE, 127)246 APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_FOREGROUND_SERVICE_SPECIAL_USE, 127); APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_SYSTEM_EXEMPT_FROM_POWER_RESTRICTIONS, 128)247 APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_SYSTEM_EXEMPT_FROM_POWER_RESTRICTIONS, 128); APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_SYSTEM_EXEMPT_FROM_HIBERNATION, 129)248 APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_SYSTEM_EXEMPT_FROM_HIBERNATION, 129); APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_SYSTEM_EXEMPT_FROM_ACTIVITY_BG_START_RESTRICTION, 130)249 APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_SYSTEM_EXEMPT_FROM_ACTIVITY_BG_START_RESTRICTION, 250 130); APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_CAPTURE_CONSENTLESS_BUGREPORT_ON_USERDEBUG_BUILD, 131)251 APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_CAPTURE_CONSENTLESS_BUGREPORT_ON_USERDEBUG_BUILD, 252 131); 253 // Op 132 was deprecated APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_USE_FULL_SCREEN_INTENT, 133)254 APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_USE_FULL_SCREEN_INTENT, 133); APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_CAMERA_SANDBOXED, 134)255 APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_CAMERA_SANDBOXED, 134); APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_RECORD_AUDIO_SANDBOXED, 135)256 APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_RECORD_AUDIO_SANDBOXED, 135); 257 } 258 259 @Test testTlsHandshake()260 public void testTlsHandshake() throws Exception { 261 TestSSLContext context = TestSSLContext.create(); 262 SSLSocket[] sockets = TestSSLSocketPair.connect(context, null, null); 263 264 if (sockets.length < 2) { 265 return; 266 } 267 sockets[0].getOutputStream().write(42); 268 Assert.assertEquals(42, sockets[1].getInputStream().read()); 269 sockets[0].close(); 270 sockets[1].close(); 271 } 272 273 @Test 274 // Start the isolated service, which logs an AppBreadcrumbReported atom, and then exit. testIsolatedProcessService()275 public void testIsolatedProcessService() throws Exception { 276 Context context = InstrumentationRegistry.getContext(); 277 Intent intent = new Intent(context, IsolatedProcessService.class); 278 context.startService(intent); 279 sleep(2_000); 280 context.stopService(intent); 281 } 282 283 @Test testAudioState()284 public void testAudioState() { 285 // TODO: This should surely be getTargetContext(), here and everywhere, but test first. 286 Context context = InstrumentationRegistry.getContext(); 287 MediaPlayer mediaPlayer = MediaPlayer.create(context, R.raw.good); 288 mediaPlayer.start(); 289 sleep(2_000); 290 mediaPlayer.stop(); 291 } 292 293 @Test testBleScanOpportunistic()294 public void testBleScanOpportunistic() { 295 ScanSettings scanSettings = new ScanSettings.Builder() 296 .setScanMode(ScanSettings.SCAN_MODE_OPPORTUNISTIC).build(); 297 performBleScan(scanSettings, null, false); 298 } 299 300 @Test testBleScanUnoptimized()301 public void testBleScanUnoptimized() { 302 ScanSettings scanSettings = new ScanSettings.Builder() 303 .setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY).build(); 304 performBleScan(scanSettings, null, false); 305 } 306 307 @Test testBleScanResult()308 public void testBleScanResult() { 309 ScanSettings scanSettings = new ScanSettings.Builder() 310 .setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY).build(); 311 ScanFilter.Builder scanFilter = new ScanFilter.Builder(); 312 performBleScan(scanSettings, Arrays.asList(scanFilter.build()), true); 313 } 314 315 @Test testBleScanInterrupted()316 public void testBleScanInterrupted() throws Exception { 317 performBleAction((bluetoothAdapter, bleScanner) -> { 318 ScanSettings scanSettings = new ScanSettings.Builder() 319 .setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY).build(); 320 ScanCallback scanCallback = new ScanCallback() { 321 @Override 322 public void onScanResult(int callbackType, ScanResult result) { 323 Log.v(TAG, "called onScanResult"); 324 } 325 326 @Override 327 public void onScanFailed(int errorCode) { 328 Log.v(TAG, "called onScanFailed"); 329 } 330 331 @Override 332 public void onBatchScanResults(List<ScanResult> results) { 333 Log.v(TAG, "called onBatchScanResults"); 334 } 335 }; 336 337 int uid = Process.myUid(); 338 int whatAtomId = 9_999; 339 340 // Get the current setting for bluetooth background scanning. 341 // Set to 0 if the setting is not found or an error occurs. 342 int initialBleScanGlobalSetting = Settings.Global.getInt( 343 InstrumentationRegistry.getTargetContext().getContentResolver(), 344 Settings.Global.BLE_SCAN_ALWAYS_AVAILABLE, 0); 345 346 // Turn off bluetooth background scanning. 347 Settings.Global.putInt(InstrumentationRegistry.getTargetContext().getContentResolver(), 348 Settings.Global.BLE_SCAN_ALWAYS_AVAILABLE, 0); 349 350 // Change state to State.ON. 351 bleScanner.startScan(null, scanSettings, scanCallback); 352 sleep(6_000); 353 writeSliceByBleScanStateChangedAtom(whatAtomId, uid, false, false, false); 354 writeSliceByBleScanStateChangedAtom(whatAtomId, uid, false, false, false); 355 356 bluetoothAdapter.disable(); 357 sleep(6_000); 358 359 // Trigger State.RESET so that new state is State.OFF. 360 if (!bluetoothAdapter.enable()) { 361 Log.e(TAG, "Could not enable bluetooth to trigger state reset"); 362 return; 363 } 364 sleep(6_000); // Wait for Bluetooth to fully turn on. 365 writeSliceByBleScanStateChangedAtom(whatAtomId, uid, false, false, false); 366 writeSliceByBleScanStateChangedAtom(whatAtomId, uid, false, false, false); 367 writeSliceByBleScanStateChangedAtom(whatAtomId, uid, false, false, false); 368 369 // Set bluetooth background scanning to original setting. 370 Settings.Global.putInt(InstrumentationRegistry.getTargetContext().getContentResolver(), 371 Settings.Global.BLE_SCAN_ALWAYS_AVAILABLE, initialBleScanGlobalSetting); 372 }); 373 } 374 writeSliceByBleScanStateChangedAtom(int atomId, int firstUid, boolean field2, boolean field3, boolean field4)375 private static void writeSliceByBleScanStateChangedAtom(int atomId, int firstUid, 376 boolean field2, boolean field3, 377 boolean field4) { 378 final StatsEvent.Builder builder = StatsEvent.newBuilder() 379 .setAtomId(atomId) 380 .writeAttributionChain(new int[]{firstUid}, new String[]{"tag1"}) 381 .writeBoolean(field2) 382 .writeBoolean(field3) 383 .writeBoolean(field4) 384 .usePooledBuffer(); 385 386 StatsLog.write(builder.build()); 387 } 388 389 /** 390 * Set up BluetoothLeScanner and perform the action in the callback. 391 * Restore Bluetooth to original state afterwards. 392 **/ performBleAction(BiConsumer<BluetoothAdapter, BluetoothLeScanner> actions)393 private static void performBleAction(BiConsumer<BluetoothAdapter, BluetoothLeScanner> actions) { 394 BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); 395 if (bluetoothAdapter == null) { 396 Log.e(TAG, "Device does not support Bluetooth"); 397 return; 398 } 399 boolean bluetoothEnabledByTest = false; 400 if (!bluetoothAdapter.isEnabled()) { 401 if (!bluetoothAdapter.enable()) { 402 Log.e(TAG, "Bluetooth is not enabled"); 403 return; 404 } 405 sleep(2_000); // Wait for Bluetooth to fully turn on. 406 bluetoothEnabledByTest = true; 407 } 408 BluetoothLeScanner bleScanner = bluetoothAdapter.getBluetoothLeScanner(); 409 if (bleScanner == null) { 410 Log.e(TAG, "Cannot access BLE scanner"); 411 return; 412 } 413 414 actions.accept(bluetoothAdapter, bleScanner); 415 416 // Restore adapter state 417 if (bluetoothEnabledByTest) { 418 bluetoothAdapter.disable(); 419 } 420 } 421 422 performBleScan(ScanSettings scanSettings, List<ScanFilter> scanFilters, boolean waitForResult)423 private static void performBleScan(ScanSettings scanSettings, List<ScanFilter> scanFilters, 424 boolean waitForResult) { 425 performBleAction((bluetoothAdapter, bleScanner) -> { 426 CountDownLatch resultsLatch = new CountDownLatch(1); 427 ScanCallback scanCallback = new ScanCallback() { 428 @Override 429 public void onScanResult(int callbackType, ScanResult result) { 430 Log.v(TAG, "called onScanResult"); 431 resultsLatch.countDown(); 432 } 433 434 @Override 435 public void onScanFailed(int errorCode) { 436 Log.v(TAG, "called onScanFailed"); 437 } 438 439 @Override 440 public void onBatchScanResults(List<ScanResult> results) { 441 Log.v(TAG, "called onBatchScanResults"); 442 resultsLatch.countDown(); 443 } 444 }; 445 446 bleScanner.startScan(scanFilters, scanSettings, scanCallback); 447 if (waitForResult) { 448 waitForReceiver(InstrumentationRegistry.getContext(), 59_000, resultsLatch, null); 449 } else { 450 sleep(2_000); 451 } 452 bleScanner.stopScan(scanCallback); 453 }); 454 } 455 456 @Test testCameraState()457 public void testCameraState() throws Exception { 458 Context context = InstrumentationRegistry.getContext(); 459 CameraManager cam = context.getSystemService(CameraManager.class); 460 String[] cameraIds = cam.getCameraIdList(); 461 if (cameraIds.length == 0) { 462 Log.e(TAG, "No camera found on device"); 463 return; 464 } 465 466 CountDownLatch latch = new CountDownLatch(1); 467 final CameraDevice.StateCallback cb = new CameraDevice.StateCallback() { 468 @Override 469 public void onOpened(CameraDevice cd) { 470 Log.i(TAG, "CameraDevice " + cd.getId() + " opened"); 471 sleep(2_000); 472 cd.close(); 473 } 474 475 @Override 476 public void onClosed(CameraDevice cd) { 477 latch.countDown(); 478 Log.i(TAG, "CameraDevice " + cd.getId() + " closed"); 479 } 480 481 @Override 482 public void onDisconnected(CameraDevice cd) { 483 Log.w(TAG, "CameraDevice " + cd.getId() + " disconnected"); 484 } 485 486 @Override 487 public void onError(CameraDevice cd, int error) { 488 Log.e(TAG, "CameraDevice " + cd.getId() + "had error " + error); 489 } 490 }; 491 492 HandlerThread handlerThread = new HandlerThread("br_handler_thread"); 493 handlerThread.start(); 494 Looper looper = handlerThread.getLooper(); 495 Handler handler = new Handler(looper); 496 497 cam.openCamera(cameraIds[0], cb, handler); 498 waitForReceiver(context, 10_000, latch, null); 499 } 500 501 @Test testFlashlight()502 public void testFlashlight() throws Exception { 503 Context context = InstrumentationRegistry.getContext(); 504 CameraManager cam = context.getSystemService(CameraManager.class); 505 String[] cameraIds = cam.getCameraIdList(); 506 boolean foundFlash = false; 507 for (int i = 0; i < cameraIds.length; i++) { 508 String id = cameraIds[i]; 509 if (cam.getCameraCharacteristics(id).get(CameraCharacteristics.FLASH_INFO_AVAILABLE)) { 510 cam.setTorchMode(id, true); 511 sleep(500); 512 cam.setTorchMode(id, false); 513 foundFlash = true; 514 break; 515 } 516 } 517 if (!foundFlash) { 518 Log.e(TAG, "No flashlight found on device"); 519 } 520 } 521 522 @Test testForegroundService()523 public void testForegroundService() throws Exception { 524 Context context = InstrumentationRegistry.getContext(); 525 // The service goes into foreground and exits shortly 526 Intent intent = new Intent(context, StatsdCtsForegroundService.class); 527 context.startService(intent); 528 sleep(500); 529 context.stopService(intent); 530 } 531 532 @Test testForegroundServiceAccessAppOp()533 public void testForegroundServiceAccessAppOp() throws Exception { 534 Context context = InstrumentationRegistry.getContext(); 535 Intent fgsIntent = new Intent(context, StatsdCtsForegroundService.class); 536 AppOpsManager appOpsManager = context.getSystemService(AppOpsManager.class); 537 538 // No foreground service session 539 noteAppOp(appOpsManager, AppOpsManager.OPSTR_COARSE_LOCATION); 540 sleep(500); 541 542 // Foreground service session 1 543 context.startService(fgsIntent); 544 while (!checkIfServiceRunning(context, StatsdCtsForegroundService.class.getName())) { 545 sleep(50); 546 } 547 noteAppOp(appOpsManager, AppOpsManager.OPSTR_CAMERA); 548 noteAppOp(appOpsManager, AppOpsManager.OPSTR_FINE_LOCATION); 549 noteAppOp(appOpsManager, AppOpsManager.OPSTR_CAMERA); 550 startAppOp(appOpsManager, AppOpsManager.OPSTR_RECORD_AUDIO); 551 noteAppOp(appOpsManager, AppOpsManager.OPSTR_RECORD_AUDIO); 552 startAppOp(appOpsManager, AppOpsManager.OPSTR_CAMERA); 553 sleep(500); 554 context.stopService(fgsIntent); 555 556 // No foreground service session 557 noteAppOp(appOpsManager, AppOpsManager.OPSTR_COARSE_LOCATION); 558 sleep(500); 559 560 // TODO(b/149098800): Start fgs a second time and log OPSTR_CAMERA again 561 } 562 563 @Test testAppOps()564 public void testAppOps() throws Exception { 565 Context context = InstrumentationRegistry.getContext(); 566 AppOpsManager appOpsManager = context.getSystemService(AppOpsManager.class); 567 568 String[] opsList = appOpsManager.getOpStrs(); 569 570 for (int i = 0; i < opsList.length; i++) { 571 String op = opsList[i]; 572 if (TextUtils.isEmpty(op) || op.startsWith("android:deprecated")) { 573 // Operation removed/deprecated 574 continue; 575 } 576 int noteCount = APP_OPS_ENUM_MAP.getOrDefault(op, opsList.length) + 1; 577 for (int j = 0; j < noteCount; j++) { 578 try { 579 noteAppOp(appOpsManager, opsList[i]); 580 } catch (SecurityException e) { 581 } 582 } 583 } 584 } 585 noteAppOp(AppOpsManager aom, String opStr)586 private void noteAppOp(AppOpsManager aom, String opStr) { 587 aom.noteOp(opStr, android.os.Process.myUid(), MY_PACKAGE_NAME, null, "statsdTest"); 588 } 589 startAppOp(AppOpsManager aom, String opStr)590 private void startAppOp(AppOpsManager aom, String opStr) { 591 aom.startOp(opStr, android.os.Process.myUid(), MY_PACKAGE_NAME, null, "statsdTest"); 592 } 593 594 /** Check if service is running. */ checkIfServiceRunning(Context context, String serviceName)595 public boolean checkIfServiceRunning(Context context, String serviceName) { 596 ActivityManager manager = context.getSystemService(ActivityManager.class); 597 for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) { 598 if (serviceName.equals(service.service.getClassName()) && service.foreground) { 599 return true; 600 } 601 } 602 return false; 603 } 604 605 @Test testGpsScan()606 public void testGpsScan() { 607 Context context = InstrumentationRegistry.getContext(); 608 final LocationManager locManager = context.getSystemService(LocationManager.class); 609 if (!locManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) { 610 Log.e(TAG, "GPS provider is not enabled"); 611 return; 612 } 613 CountDownLatch latch = new CountDownLatch(1); 614 615 final LocationListener locListener = new LocationListener() { 616 public void onLocationChanged(Location location) { 617 Log.v(TAG, "onLocationChanged: location has been obtained"); 618 } 619 620 public void onProviderDisabled(String provider) { 621 Log.w(TAG, "onProviderDisabled " + provider); 622 } 623 624 public void onProviderEnabled(String provider) { 625 Log.w(TAG, "onProviderEnabled " + provider); 626 } 627 628 public void onStatusChanged(String provider, int status, Bundle extras) { 629 Log.w(TAG, "onStatusChanged " + provider + " " + status); 630 } 631 }; 632 633 new AsyncTask<Void, Void, Void>() { 634 @Override 635 protected Void doInBackground(Void... params) { 636 Looper.prepare(); 637 locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 990, 0, 638 locListener); 639 sleep(1_000); 640 locManager.removeUpdates(locListener); 641 latch.countDown(); 642 return null; 643 } 644 }.execute(); 645 646 waitForReceiver(context, 59_000, latch, null); 647 } 648 649 @Test testGpsStatus()650 public void testGpsStatus() { 651 Context context = InstrumentationRegistry.getContext(); 652 final LocationManager locManager = context.getSystemService(LocationManager.class); 653 654 if (!locManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) { 655 Log.e(TAG, "GPS provider is not enabled"); 656 return; 657 } 658 659 // Time out set to 85 seconds (5 seconds for sleep and a possible 85 seconds if TTFF takes 660 // max time which would be around 90 seconds. 661 // This is based on similar location cts test timeout values. 662 final int TIMEOUT_IN_MSEC = 85_000; 663 final int SLEEP_TIME_IN_MSEC = 5_000; 664 665 final CountDownLatch mLatchNetwork = new CountDownLatch(1); 666 667 final LocationListener locListener = location -> { 668 Log.v(TAG, "onLocationChanged: location has been obtained"); 669 mLatchNetwork.countDown(); 670 }; 671 672 // fetch the networklocation first to make sure the ttff is not flaky 673 if (locManager.getProvider(LocationManager.NETWORK_PROVIDER) != null) { 674 Log.i(TAG, "Request Network Location updates."); 675 locManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 676 0 /* minTime*/, 677 0 /* minDistance */, 678 locListener, 679 Looper.getMainLooper()); 680 } 681 waitForReceiver(context, TIMEOUT_IN_MSEC, mLatchNetwork, null); 682 683 // TTFF could take up to 90 seconds, thus we need to wait till TTFF does occur if it does 684 // not occur in the first SLEEP_TIME_IN_MSEC 685 final CountDownLatch mLatchTtff = new CountDownLatch(1); 686 687 GnssStatus.Callback gnssStatusCallback = new GnssStatus.Callback() { 688 @Override 689 public void onStarted() { 690 Log.v(TAG, "Gnss Status Listener Started"); 691 } 692 693 @Override 694 public void onStopped() { 695 Log.v(TAG, "Gnss Status Listener Stopped"); 696 } 697 698 @Override 699 public void onFirstFix(int ttffMillis) { 700 Log.v(TAG, "Gnss Status Listener Received TTFF"); 701 mLatchTtff.countDown(); 702 } 703 704 @Override 705 public void onSatelliteStatusChanged(GnssStatus status) { 706 Log.v(TAG, "Gnss Status Listener Received Status Update"); 707 } 708 }; 709 710 boolean gnssStatusCallbackAdded = locManager.registerGnssStatusCallback( 711 gnssStatusCallback, new Handler(Looper.getMainLooper())); 712 if (!gnssStatusCallbackAdded) { 713 // Registration of GnssMeasurements listener has failed, this indicates a platform bug. 714 Log.e(TAG, "Failed to start gnss status callback"); 715 } 716 717 locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 718 0, 719 0 /* minDistance */, 720 locListener, 721 Looper.getMainLooper()); 722 sleep(SLEEP_TIME_IN_MSEC); 723 waitForReceiver(context, TIMEOUT_IN_MSEC, mLatchTtff, null); 724 locManager.removeUpdates(locListener); 725 locManager.unregisterGnssStatusCallback(gnssStatusCallback); 726 } 727 728 @Test testScreenBrightness()729 public void testScreenBrightness() { 730 Context context = InstrumentationRegistry.getContext(); 731 PowerManager pm = context.getSystemService(PowerManager.class); 732 PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK | 733 PowerManager.ACQUIRE_CAUSES_WAKEUP, "StatsdBrightnessTest"); 734 wl.acquire(); 735 sleep(500); 736 737 setScreenBrightness(47); 738 sleep(500); 739 setScreenBrightness(100); 740 sleep(500); 741 742 743 wl.release(); 744 } 745 746 @Test testSyncState()747 public void testSyncState() throws Exception { 748 749 Context context = InstrumentationRegistry.getContext(); 750 StatsdAuthenticator.removeAllAccounts(context); 751 AccountManager am = context.getSystemService(AccountManager.class); 752 CountDownLatch latch = StatsdSyncAdapter.resetCountDownLatch(); 753 754 Account account = StatsdAuthenticator.getTestAccount(); 755 StatsdAuthenticator.ensureTestAccount(context); 756 sleep(500); 757 758 // Just force set is syncable. 759 ContentResolver.setMasterSyncAutomatically(true); 760 sleep(500); 761 ContentResolver.setIsSyncable(account, StatsdProvider.AUTHORITY, 1); 762 // Wait for the first (automatic) sync to finish 763 waitForReceiver(context, 120_000, latch, null); 764 765 //Sleep for 500ms, since we assert each start/stop to be ~500ms apart. 766 sleep(500); 767 768 // Request and wait for the second sync to finish 769 latch = StatsdSyncAdapter.resetCountDownLatch(); 770 StatsdSyncAdapter.requestSync(account); 771 waitForReceiver(context, 120_000, latch, null); 772 StatsdAuthenticator.removeAllAccounts(context); 773 } 774 775 @Test testScheduledJob()776 public void testScheduledJob() throws Exception { 777 final ComponentName name = new ComponentName(MY_PACKAGE_NAME, 778 StatsdJobService.class.getName()); 779 780 Context context = InstrumentationRegistry.getContext(); 781 JobScheduler js = context.getSystemService(JobScheduler.class); 782 assertWithMessage("JobScheduler service not available").that(js).isNotNull(); 783 784 JobInfo.Builder builder = new JobInfo.Builder(1, name); 785 builder.setOverrideDeadline(0); 786 JobInfo job = builder.build(); 787 788 CountDownLatch latch = StatsdJobService.resetCountDownLatch(); 789 js.schedule(job); 790 waitForReceiver(context, 5_000, latch, null); 791 } 792 793 @Test testScheduledJob_CancelledJob()794 public void testScheduledJob_CancelledJob() throws Exception { 795 final ComponentName name = new ComponentName(MY_PACKAGE_NAME, 796 StatsdJobService.class.getName()); 797 798 Context context = InstrumentationRegistry.getContext(); 799 JobScheduler js = context.getSystemService(JobScheduler.class); 800 assertWithMessage("JobScheduler service not available").that(js).isNotNull(); 801 802 JobInfo.Builder builder = new JobInfo.Builder(1, name); 803 builder.setMinimumLatency(60_000L); 804 JobInfo job = builder.build(); 805 806 js.schedule(job); 807 js.cancel(1); 808 } 809 810 @Test testScheduledJobPriority()811 public void testScheduledJobPriority() throws Exception { 812 final ComponentName name = 813 new ComponentName(MY_PACKAGE_NAME, StatsdJobService.class.getName()); 814 815 Context context = InstrumentationRegistry.getContext(); 816 JobScheduler js = context.getSystemService(JobScheduler.class); 817 assertWithMessage("JobScheduler service not available").that(js).isNotNull(); 818 819 final int[] priorities = { 820 JobInfo.PRIORITY_HIGH, JobInfo.PRIORITY_DEFAULT, 821 JobInfo.PRIORITY_LOW, JobInfo.PRIORITY_MIN}; 822 for (int priority : priorities) { 823 JobInfo job = new JobInfo.Builder(priority, name) 824 .setOverrideDeadline(0) 825 .setPriority(priority) 826 .build(); 827 828 CountDownLatch latch = StatsdJobService.resetCountDownLatch(); 829 js.schedule(job); 830 waitForReceiver(context, 5_000, latch, null); 831 } 832 } 833 834 @Test testVibratorState()835 public void testVibratorState() { 836 Context context = InstrumentationRegistry.getContext(); 837 Vibrator vib = context.getSystemService(Vibrator.class); 838 if (vib.hasVibrator()) { 839 vib.vibrate(VibrationEffect.createOneShot( 840 500 /* ms */, VibrationEffect.DEFAULT_AMPLITUDE)); 841 } 842 // Sleep so that the app does not get killed. 843 sleep(1000); 844 } 845 846 @Test testWakelockState()847 public void testWakelockState() { 848 Context context = InstrumentationRegistry.getContext(); 849 PowerManager pm = context.getSystemService(PowerManager.class); 850 PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, 851 "StatsdPartialWakelock"); 852 wl.acquire(); 853 sleep(500); 854 wl.release(); 855 } 856 857 @Test testSliceByWakelockState()858 public void testSliceByWakelockState() { 859 int uid = Process.myUid(); 860 int whatAtomId = 9_998; 861 int wakelockType = PowerManager.PARTIAL_WAKE_LOCK; 862 String tag = "StatsdPartialWakelock"; 863 864 Context context = InstrumentationRegistry.getContext(); 865 PowerManager pm = context.getSystemService(PowerManager.class); 866 PowerManager.WakeLock wl = pm.newWakeLock(wakelockType, tag); 867 868 wl.acquire(); 869 sleep(500); 870 writeSliceByWakelockStateChangedAtom(whatAtomId, uid, wakelockType, tag); 871 writeSliceByWakelockStateChangedAtom(whatAtomId, uid, wakelockType, tag); 872 wl.acquire(); 873 sleep(500); 874 writeSliceByWakelockStateChangedAtom(whatAtomId, uid, wakelockType, tag); 875 writeSliceByWakelockStateChangedAtom(whatAtomId, uid, wakelockType, tag); 876 writeSliceByWakelockStateChangedAtom(whatAtomId, uid, wakelockType, tag); 877 wl.release(); 878 sleep(500); 879 writeSliceByWakelockStateChangedAtom(whatAtomId, uid, wakelockType, tag); 880 wl.release(); 881 sleep(500); 882 writeSliceByWakelockStateChangedAtom(whatAtomId, uid, wakelockType, tag); 883 writeSliceByWakelockStateChangedAtom(whatAtomId, uid, wakelockType, tag); 884 writeSliceByWakelockStateChangedAtom(whatAtomId, uid, wakelockType, tag); 885 } 886 writeSliceByWakelockStateChangedAtom(int atomId, int firstUid, int field2, String field3)887 private static void writeSliceByWakelockStateChangedAtom(int atomId, int firstUid, 888 int field2, String field3) { 889 final StatsEvent.Builder builder = StatsEvent.newBuilder() 890 .setAtomId(atomId) 891 .writeAttributionChain(new int[]{firstUid}, new String[]{"tag1"}) 892 .writeInt(field2) 893 .writeString(field3) 894 .usePooledBuffer(); 895 896 StatsLog.write(builder.build()); 897 } 898 899 @Test testWakelockLoad()900 public void testWakelockLoad() { 901 final int NUM_THREADS = 16; 902 CountDownLatch latch = new CountDownLatch(NUM_THREADS); 903 for (int i = 0; i < NUM_THREADS; i++) { 904 Thread t = new Thread(new WakelockLoadTestRunnable("StatsdPartialWakelock" + i, latch)); 905 t.start(); 906 } 907 waitForReceiver(null, 120_000, latch, null); 908 } 909 910 @Test testWifiLockHighPerf()911 public void testWifiLockHighPerf() throws Exception { 912 Context context = InstrumentationRegistry.getContext(); 913 boolean wifiConnected = isWifiConnected(context); 914 Assert.assertTrue( 915 "Wifi is not connected. The test expects Wifi to be connected before the run", 916 wifiConnected); 917 918 WifiManager wm = context.getSystemService(WifiManager.class); 919 WifiManager.WifiLock lock = 920 wm.createWifiLock(WifiManager.WIFI_MODE_FULL_HIGH_PERF, "StatsdCTSWifiLock"); 921 lock.acquire(); 922 sleep(500); 923 lock.release(); 924 } 925 926 @Test testWifiConnected()927 public void testWifiConnected() throws Exception { 928 Context context = InstrumentationRegistry.getContext(); 929 boolean wifiConnected = isWifiConnected(context); 930 Assert.assertTrue( 931 "Wifi is not connected. The test expects Wifi to be connected before the run", 932 wifiConnected); 933 } 934 935 @Test testWifiMulticastLock()936 public void testWifiMulticastLock() { 937 Context context = InstrumentationRegistry.getContext(); 938 WifiManager wm = context.getSystemService(WifiManager.class); 939 WifiManager.MulticastLock lock = wm.createMulticastLock("StatsdCTSMulticastLock"); 940 lock.acquire(); 941 sleep(500); 942 lock.release(); 943 } 944 945 @Test 946 /** Does two wifi scans. */ 947 // TODO: Copied this from BatterystatsValidation but we probably don't need to wait for results. testWifiScan()948 public void testWifiScan() { 949 Context context = InstrumentationRegistry.getContext(); 950 IntentFilter intentFilter = new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION); 951 // Sometimes a scan was already running (from a different uid), so the first scan doesn't 952 // start when requested. Therefore, additionally wait for whatever scan is currently running 953 // to finish, then request a scan again - at least one of these two scans should be 954 // attributed to this app. 955 for (int i = 0; i < 2; i++) { 956 CountDownLatch onReceiveLatch = new CountDownLatch(1); 957 BroadcastReceiver receiver = registerReceiver(context, onReceiveLatch, intentFilter); 958 context.getSystemService(WifiManager.class).startScan(); 959 waitForReceiver(context, 60_000, onReceiveLatch, receiver); 960 } 961 } 962 963 @Test testWifiReconnect()964 public void testWifiReconnect() throws Exception { 965 Context context = InstrumentationRegistry.getContext(); 966 boolean wifiConnected = isWifiConnected(context); 967 Assert.assertTrue( 968 "Wifi is not connected. The test expects Wifi to be connected before the run", 969 wifiConnected); 970 971 wifiDisconnect(context); 972 sleep(500); 973 wifiReconnect(context); 974 sleep(500); 975 } 976 977 @Test testSimpleCpu()978 public void testSimpleCpu() { 979 long timestamp = System.currentTimeMillis(); 980 for (int i = 0; i < 10000; i++) { 981 timestamp += i; 982 } 983 Log.i(TAG, "The answer is " + timestamp); 984 } 985 986 @Test testWriteRawTestAtom()987 public void testWriteRawTestAtom() throws Exception { 988 Context context = InstrumentationRegistry.getTargetContext(); 989 ApplicationInfo appInfo = context.getPackageManager() 990 .getApplicationInfo(context.getPackageName(), 0); 991 int[] uids = {1234, appInfo.uid}; 992 String[] tags = {"tag1", "tag2"}; 993 byte[] experimentIds = {8, 1, 8, 2, 8, 3}; // Corresponds to 1, 2, 3. 994 995 int[] int32Array = {3, 6}; 996 long[] int64Array = {1000L, 1002L}; 997 float[] floatArray = {0.3f, 0.09f}; 998 String[] stringArray = {"str1", "str2"}; 999 boolean[] boolArray = {true, false}; 1000 int[] enumArray = {StatsLogStatsdCts.TEST_ATOM_REPORTED__STATE__OFF, 1001 StatsLogStatsdCts.TEST_ATOM_REPORTED__STATE__ON}; 1002 1003 StatsLogStatsdCts.write(StatsLogStatsdCts.TEST_ATOM_REPORTED, uids, tags, 42, 1004 Long.MAX_VALUE, 3.14f, "This is a basic test!", false, 1005 StatsLogStatsdCts.TEST_ATOM_REPORTED__STATE__ON, experimentIds, int32Array, 1006 int64Array, floatArray, stringArray, boolArray, enumArray); 1007 1008 // All nulls. Should get dropped since cts app is not in the attribution chain. 1009 StatsLogStatsdCts.write(StatsLogStatsdCts.TEST_ATOM_REPORTED, null, null, 0, 0, 0f, null, 1010 false, StatsLogStatsdCts.TEST_ATOM_REPORTED__STATE__ON, null, null, null, null, 1011 null, null, null); 1012 1013 // Null tag in attribution chain. 1014 int[] uids2 = {9999, appInfo.uid}; 1015 String[] tags2 = {"tag9999", null}; 1016 StatsLogStatsdCts.write(StatsLogStatsdCts.TEST_ATOM_REPORTED, uids2, tags2, 100, 1017 Long.MIN_VALUE, -2.5f, "Test null uid", true, 1018 StatsLogStatsdCts.TEST_ATOM_REPORTED__STATE__UNKNOWN, experimentIds, int32Array, 1019 int64Array, floatArray, stringArray, boolArray, enumArray); 1020 1021 // Non chained non-null 1022 StatsLogStatsdCts.write_non_chained(StatsLogStatsdCts.TEST_ATOM_REPORTED, appInfo.uid, 1023 "tag1", -256, -1234567890L, 42.01f, "Test non chained", true, 1024 StatsLogStatsdCts.TEST_ATOM_REPORTED__STATE__OFF, experimentIds, new int[0], 1025 new long[0], new float[0], new String[0], new boolean[0], new int[0]); 1026 1027 // Non chained all null 1028 StatsLogStatsdCts.write_non_chained(StatsLogStatsdCts.TEST_ATOM_REPORTED, appInfo.uid, null, 1029 0, 0, 0f, null, true, StatsLogStatsdCts.TEST_ATOM_REPORTED__STATE__OFF, null, null, 1030 null, null, null, null, null); 1031 } 1032 1033 @Test testWriteExtensionTestAtom()1034 public void testWriteExtensionTestAtom() throws Exception { 1035 Context context = InstrumentationRegistry.getTargetContext(); 1036 ApplicationInfo appInfo = context.getPackageManager() 1037 .getApplicationInfo(context.getPackageName(), 0); 1038 int[] uids = {1234, appInfo.uid}; 1039 String[] tags = {"tag1", "tag2"}; 1040 byte[] testAtomNestedMsg = {8, 1, 8, 2, 8, 3}; // Corresponds to 1, 2, 3. 1041 1042 int[] int32Array = {3, 6}; 1043 long[] int64Array = {1000L, 1002L}; 1044 float[] floatArray = {0.3f, 0.09f}; 1045 String[] stringArray = {"str1", "str2"}; 1046 boolean[] boolArray = {true, false}; 1047 int[] enumArray = {StatsLogStatsdCts.TEST_EXTENSION_ATOM_REPORTED__STATE__OFF, 1048 StatsLogStatsdCts.TEST_EXTENSION_ATOM_REPORTED__STATE__ON}; 1049 1050 StatsLogStatsdCts.write(StatsLogStatsdCts.TEST_EXTENSION_ATOM_REPORTED, uids, tags, 42, 1051 Long.MAX_VALUE, 3.14f, "This is a basic test!", false, 1052 StatsLogStatsdCts.TEST_EXTENSION_ATOM_REPORTED__STATE__ON, testAtomNestedMsg, 1053 int32Array, 1054 int64Array, floatArray, stringArray, boolArray, enumArray); 1055 1056 // All nulls. Should get dropped since cts app is not in the attribution chain. 1057 StatsLogStatsdCts.write(StatsLogStatsdCts.TEST_EXTENSION_ATOM_REPORTED, null, null, 0, 0, 1058 0f, null, 1059 false, StatsLogStatsdCts.TEST_EXTENSION_ATOM_REPORTED__STATE__ON, null, null, null, 1060 null, 1061 null, null, null); 1062 1063 // Null tag in attribution chain. 1064 int[] uids2 = {9999, appInfo.uid}; 1065 String[] tags2 = {"tag9999", null}; 1066 StatsLogStatsdCts.write(StatsLogStatsdCts.TEST_EXTENSION_ATOM_REPORTED, uids2, tags2, 100, 1067 Long.MIN_VALUE, -2.5f, "Test null uid", true, 1068 StatsLogStatsdCts.TEST_EXTENSION_ATOM_REPORTED__STATE__UNKNOWN, testAtomNestedMsg, 1069 int32Array, 1070 int64Array, floatArray, stringArray, boolArray, enumArray); 1071 1072 // Non chained non-null 1073 StatsLogStatsdCts.write_non_chained(StatsLogStatsdCts.TEST_EXTENSION_ATOM_REPORTED, 1074 appInfo.uid, 1075 "tag1", -256, -1234567890L, 42.01f, "Test non chained", true, 1076 StatsLogStatsdCts.TEST_EXTENSION_ATOM_REPORTED__STATE__OFF, testAtomNestedMsg, 1077 new int[0], 1078 new long[0], new float[0], new String[0], new boolean[0], new int[0]); 1079 1080 // Non chained all null 1081 StatsLogStatsdCts.write_non_chained(StatsLogStatsdCts.TEST_EXTENSION_ATOM_REPORTED, 1082 appInfo.uid, null, 1083 0, 0, 0f, null, true, StatsLogStatsdCts.TEST_EXTENSION_ATOM_REPORTED__STATE__OFF, 1084 null, null, 1085 null, null, null, null, null); 1086 } 1087 1088 /** 1089 * Bring up and generate some traffic on cellular data connection. 1090 */ 1091 @Test testGenerateMobileTraffic()1092 public void testGenerateMobileTraffic() throws Exception { 1093 final Context context = InstrumentationRegistry.getContext(); 1094 doGenerateNetworkTraffic(context, NetworkCapabilities.TRANSPORT_CELLULAR); 1095 } 1096 1097 /** 1098 * Force poll NetworkStatsService to get most updated network stats from lower layer. 1099 */ 1100 @Test testForcePollNetworkStats()1101 public void testForcePollNetworkStats() throws Exception { 1102 final Context context = InstrumentationRegistry.getContext(); 1103 final NetworkStatsManager nsm = context.getSystemService(NetworkStatsManager.class); 1104 try { 1105 nsm.setPollForce(true); 1106 // This query is for triggering force poll NetworkStatsService. 1107 nsm.querySummaryForUser(ConnectivityManager.TYPE_WIFI, null, Long.MIN_VALUE, 1108 Long.MAX_VALUE); 1109 } catch (RemoteException e) { 1110 Log.e(TAG, "doPollNetworkStats failed with " + e); 1111 } 1112 } 1113 1114 // Constants which are locally used by doGenerateNetworkTraffic. 1115 private static final int NETWORK_TIMEOUT_MILLIS = 15000; 1116 private static final String HTTPS_HOST_URL = 1117 "https://connectivitycheck.gstatic.com/generate_204"; 1118 doGenerateNetworkTraffic(@onNull Context context, int transport)1119 private void doGenerateNetworkTraffic(@NonNull Context context, int transport) 1120 throws InterruptedException { 1121 final ConnectivityManager cm = context.getSystemService(ConnectivityManager.class); 1122 final NetworkRequest request = new NetworkRequest.Builder().addCapability( 1123 NetworkCapabilities.NET_CAPABILITY_INTERNET).addTransportType(transport).build(); 1124 final CtsNetUtils.TestNetworkCallback callback = new CtsNetUtils.TestNetworkCallback(); 1125 1126 // Request network, and make http query when the network is available. 1127 cm.requestNetwork(request, callback); 1128 1129 // If network is not available, throws IllegalStateException. 1130 final Network network = callback.waitForAvailable(); 1131 if (network == null) { 1132 throw new IllegalStateException("network with transport " + transport 1133 + " is not available."); 1134 } 1135 1136 final long startTime = SystemClock.elapsedRealtime(); 1137 try { 1138 exerciseRemoteHost(cm, network, new URL(HTTPS_HOST_URL)); 1139 Log.i(TAG, "exerciseRemoteHost successful in " + (SystemClock.elapsedRealtime() 1140 - startTime) + " ms"); 1141 } catch (Exception e) { 1142 Log.e(TAG, "exerciseRemoteHost failed in " + (SystemClock.elapsedRealtime() 1143 - startTime) + " ms: " + e); 1144 } finally { 1145 cm.unregisterNetworkCallback(callback); 1146 } 1147 } 1148 1149 /** 1150 * Generate traffic on specified network. 1151 */ exerciseRemoteHost(@onNull ConnectivityManager cm, @NonNull Network network, @NonNull URL url)1152 private void exerciseRemoteHost(@NonNull ConnectivityManager cm, @NonNull Network network, 1153 @NonNull URL url) throws Exception { 1154 cm.bindProcessToNetwork(network); 1155 HttpURLConnection urlc = null; 1156 try { 1157 urlc = (HttpURLConnection) network.openConnection(url); 1158 urlc.setConnectTimeout(NETWORK_TIMEOUT_MILLIS); 1159 urlc.setUseCaches(false); 1160 urlc.connect(); 1161 } finally { 1162 if (urlc != null) { 1163 urlc.disconnect(); 1164 } 1165 } 1166 } 1167 1168 // ------- Helper methods 1169 1170 /** Puts the current thread to sleep. */ sleep(int millis)1171 static void sleep(int millis) { 1172 try { 1173 Thread.sleep(millis); 1174 } catch (InterruptedException e) { 1175 Log.e(TAG, "Interrupted exception while sleeping", e); 1176 } 1177 } 1178 1179 /** Register receiver to determine when given action is complete. */ registerReceiver( Context ctx, CountDownLatch onReceiveLatch, IntentFilter intentFilter)1180 private static BroadcastReceiver registerReceiver( 1181 Context ctx, CountDownLatch onReceiveLatch, IntentFilter intentFilter) { 1182 BroadcastReceiver receiver = new BroadcastReceiver() { 1183 @Override 1184 public void onReceive(Context context, Intent intent) { 1185 Log.d(TAG, "Received broadcast."); 1186 onReceiveLatch.countDown(); 1187 } 1188 }; 1189 // Run Broadcast receiver in a different thread since the main thread will wait. 1190 HandlerThread handlerThread = new HandlerThread("br_handler_thread"); 1191 handlerThread.start(); 1192 Looper looper = handlerThread.getLooper(); 1193 Handler handler = new Handler(looper); 1194 ctx.registerReceiver(receiver, intentFilter, null, handler); 1195 return receiver; 1196 } 1197 1198 /** 1199 * Uses the receiver to wait until the action is complete. ctx and receiver may be null if no 1200 * receiver is needed to be unregistered. 1201 */ waitForReceiver(Context ctx, int maxWaitTimeMs, CountDownLatch latch, BroadcastReceiver receiver)1202 private static void waitForReceiver(Context ctx, 1203 int maxWaitTimeMs, CountDownLatch latch, BroadcastReceiver receiver) { 1204 try { 1205 boolean didFinish = latch.await(maxWaitTimeMs, TimeUnit.MILLISECONDS); 1206 if (didFinish) { 1207 Log.v(TAG, "Finished performing action"); 1208 } else { 1209 // This is not necessarily a problem. If we just want to make sure a count was 1210 // recorded for the request, it doesn't matter if the action actually finished. 1211 Log.w(TAG, "Did not finish in specified time."); 1212 } 1213 } catch (InterruptedException e) { 1214 Log.e(TAG, "Interrupted exception while awaiting action to finish", e); 1215 } 1216 if (ctx != null && receiver != null) { 1217 ctx.unregisterReceiver(receiver); 1218 } 1219 } 1220 setScreenBrightness(int brightness)1221 private static void setScreenBrightness(int brightness) { 1222 runShellCommand("settings put system screen_brightness " + brightness); 1223 } 1224 1225 private static final int WIFI_CONNECT_TIMEOUT_MILLIS = 30_000; 1226 wifiDisconnect(Context context)1227 public void wifiDisconnect(Context context) throws Exception { 1228 WifiManager wifiManager = context.getSystemService(WifiManager.class); 1229 ShellIdentityUtils.invokeWithShellPermissions(() -> wifiManager.disconnect()); 1230 1231 PollingCheck.check( 1232 "Timed out waiting for Wifi to become disconnected", 1233 WIFI_CONNECT_TIMEOUT_MILLIS, 1234 () -> !isWifiConnected(context)); 1235 } 1236 wifiReconnect(Context context)1237 public void wifiReconnect(Context context) throws Exception { 1238 WifiManager wifiManager = context.getSystemService(WifiManager.class); 1239 ShellIdentityUtils.invokeWithShellPermissions(() -> wifiManager.reconnect()); 1240 1241 PollingCheck.check( 1242 "Timed out waiting for Wifi to become connected", 1243 WIFI_CONNECT_TIMEOUT_MILLIS, 1244 () -> isWifiConnected(context)); 1245 } 1246 isWifiConnected(Context context)1247 private boolean isWifiConnected(Context context) throws Exception { 1248 ConnectivityManager connManager = context.getSystemService(ConnectivityManager.class); 1249 if (connManager == null) { 1250 return false; 1251 } 1252 1253 Network[] networks = connManager.getAllNetworks(); 1254 for (Network network : networks) { 1255 if (network == null) { 1256 continue; 1257 } 1258 1259 NetworkCapabilities caps = connManager.getNetworkCapabilities(network); 1260 if (caps == null) { 1261 continue; 1262 } 1263 1264 if (caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) { 1265 return true; 1266 } 1267 } 1268 1269 return false; 1270 } 1271 1272 @Test testGameState()1273 public void testGameState() throws Exception { 1274 Context context = InstrumentationRegistry.getContext(); 1275 GameManager gameManager = context.getSystemService(GameManager.class); 1276 gameManager.setGameState(new GameState(true, GameState.MODE_CONTENT, 1, 2)); 1277 } 1278 1279 @Test testSetGameMode()1280 public void testSetGameMode() throws Exception { 1281 Context context = InstrumentationRegistry.getContext(); 1282 GameManager gameManager = context.getSystemService(GameManager.class); 1283 assertNotNull(gameManager); 1284 assertNotNull(context.getPackageName()); 1285 ShellIdentityUtils.invokeMethodWithShellPermissionsNoReturn(gameManager, 1286 (gm) -> gm.setGameMode(context.getPackageName(), 1287 GameManager.GAME_MODE_PERFORMANCE), "android.permission.MANAGE_GAME_MODE"); 1288 ShellIdentityUtils.invokeMethodWithShellPermissionsNoReturn(gameManager, 1289 (gm) -> gm.setGameMode(context.getPackageName(), 1290 GameManager.GAME_MODE_BATTERY), "android.permission.MANAGE_GAME_MODE"); 1291 } 1292 1293 @Test testUpdateCustomGameModeConfiguration()1294 public void testUpdateCustomGameModeConfiguration() throws Exception { 1295 Context context = InstrumentationRegistry.getContext(); 1296 GameManager gameManager = context.getSystemService(GameManager.class); 1297 assertNotNull(gameManager); 1298 assertNotNull(context.getPackageName()); 1299 ShellIdentityUtils.invokeMethodWithShellPermissionsNoReturn(gameManager, 1300 (gm) -> gm.updateCustomGameModeConfiguration(context.getPackageName(), 1301 new GameModeConfiguration.Builder() 1302 .setScalingFactor(0.5f) 1303 .setFpsOverride(30).build())); 1304 ShellIdentityUtils.invokeMethodWithShellPermissionsNoReturn(gameManager, 1305 (gm) -> gm.updateCustomGameModeConfiguration(context.getPackageName(), 1306 new GameModeConfiguration.Builder() 1307 .setScalingFactor(0.9f) 1308 .setFpsOverride(60).build())); 1309 } 1310 1311 @Test testCreateHintSession()1312 public void testCreateHintSession() throws Exception { 1313 final long targetNs = 16666666L; 1314 final int firstApiLevel = PropertyUtil.getFirstApiLevel(); 1315 Context context = InstrumentationRegistry.getContext(); 1316 PerformanceHintManager phm = context.getSystemService(PerformanceHintManager.class); 1317 1318 assertNotNull(phm); 1319 1320 // If the device does not support ADPF hint session, 1321 // getPreferredUpdateRateNanos() returns -1. 1322 // We only test the devices supporting it and will check 1323 // if assumption fails in PerformanceHintManagerStatsTests#testCreateHintSessionStatsd 1324 assumeTrue(phm.getPreferredUpdateRateNanos() != -1); 1325 1326 PerformanceHintManager.Session session = 1327 phm.createHintSession(new int[]{Process.myPid()}, targetNs); 1328 1329 if (firstApiLevel < Build.VERSION_CODES.S) { 1330 assumeNotNull(session); 1331 } else { 1332 assertNotNull(session); 1333 } 1334 } 1335 1336 @Test testMediaDrmAtoms()1337 public void testMediaDrmAtoms() throws Exception { 1338 UUID clearKeyUuid = new UUID(0xe2719d58a985b3c9L, 0x781ab030af78d30eL); 1339 byte[] sid = null; 1340 final int OEM_ERROR = 123; 1341 final int ERROR_CONTEXT = 456; 1342 final int ANDROID_U = 14; 1343 try (MediaDrm drm = new MediaDrm(clearKeyUuid)) { 1344 if (getClearkeyVersionInt(drm) >= ANDROID_U) { 1345 drm.setPropertyString("oemError", Integer.toString(OEM_ERROR)); 1346 drm.setPropertyString("errorContext", Integer.toString(ERROR_CONTEXT)); 1347 } 1348 for (int i = 0; i < 2; i++) { 1349 // Mock error is set per-session 1350 drm.setPropertyString("drmErrorTest", "lostState"); 1351 sid = drm.openSession(); 1352 Assert.assertNotNull("null session id", sid); 1353 try { 1354 drm.closeSession(sid); 1355 } catch (MediaDrm.MediaDrmStateException e) { 1356 Log.d(TAG, "expected for lost state"); 1357 } 1358 } 1359 } 1360 } 1361 getClearkeyVersionInt(MediaDrm drm)1362 private int getClearkeyVersionInt(MediaDrm drm) { 1363 try { 1364 return Integer.parseInt(drm.getPropertyString("version")); 1365 } catch (Exception e) { 1366 return Integer.MIN_VALUE; 1367 } 1368 } 1369 } 1370