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