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