Remove location and app usage from ODP service.
Bug: 290256559
Test: OnDevicePersonalizationManagingServicesTests
Change-Id: I28a3cf58d32c71b2d68a0a58e79828c2b8ca57bb
diff --git a/src/com/android/ondevicepersonalization/services/OnDevicePersonalizationConfigServiceDelegate.java b/src/com/android/ondevicepersonalization/services/OnDevicePersonalizationConfigServiceDelegate.java
index fe6241a..c6738e3 100644
--- a/src/com/android/ondevicepersonalization/services/OnDevicePersonalizationConfigServiceDelegate.java
+++ b/src/com/android/ondevicepersonalization/services/OnDevicePersonalizationConfigServiceDelegate.java
@@ -88,7 +88,6 @@
UserDataCollector.getInstance(mContext);
userDataCollector.clearUserData(userData);
userDataCollector.clearMetadata();
- userDataCollector.clearDatabase();
// TODO(b/302018665): replicate system server storage to T devices.
if (!SdkLevel.isAtLeastU()) {
diff --git a/src/com/android/ondevicepersonalization/services/data/OnDevicePersonalizationDbHelper.java b/src/com/android/ondevicepersonalization/services/data/OnDevicePersonalizationDbHelper.java
index c8981e3..538bf8b 100644
--- a/src/com/android/ondevicepersonalization/services/data/OnDevicePersonalizationDbHelper.java
+++ b/src/com/android/ondevicepersonalization/services/data/OnDevicePersonalizationDbHelper.java
@@ -26,7 +26,6 @@
import com.android.ondevicepersonalization.services.data.events.EventStateContract;
import com.android.ondevicepersonalization.services.data.events.EventsContract;
import com.android.ondevicepersonalization.services.data.events.QueriesContract;
-import com.android.ondevicepersonalization.services.data.user.UserDataTables;
import com.android.ondevicepersonalization.services.data.vendor.VendorSettingsContract;
/**
@@ -82,14 +81,6 @@
db.execSQL(QueriesContract.QueriesEntry.CREATE_TABLE_STATEMENT);
db.execSQL(EventsContract.EventsEntry.CREATE_TABLE_STATEMENT);
db.execSQL(EventStateContract.EventStateEntry.CREATE_TABLE_STATEMENT);
-
- // User data tables and indexes.
- db.execSQL(UserDataTables.LocationHistory.CREATE_TABLE_STATEMENT);
- db.execSQL(UserDataTables.LocationHistory.CREATE_INDEXES_STATEMENT);
- db.execSQL(UserDataTables.AppUsageHistory.CREATE_TABLE_STATEMENT);
- db.execSQL(UserDataTables.AppUsageHistory.CREATE_STARTING_TIME_SEC_INDEX_STATEMENT);
- db.execSQL(UserDataTables.AppUsageHistory.CREATE_ENDING_TIME_SEC_INDEX_STATEMENT);
- db.execSQL(UserDataTables.AppUsageHistory.CREATE_TOTAL_TIME_USED_SEC_INDEX_STATEMENT);
}
@Override
diff --git a/src/com/android/ondevicepersonalization/services/data/user/AppUsageEntry.java b/src/com/android/ondevicepersonalization/services/data/user/AppUsageEntry.java
deleted file mode 100644
index 1378f16..0000000
--- a/src/com/android/ondevicepersonalization/services/data/user/AppUsageEntry.java
+++ /dev/null
@@ -1,51 +0,0 @@
-/*
- * Copyright (C) 2022 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ondevicepersonalization.services.data.user;
-
-import androidx.annotation.NonNull;
-
-/** App usage record for ODA internal use. */
-public class AppUsageEntry {
- // App package name
- public String packageName = null;
-
- // Starting timestamp of the collection cycle
- public long startTimeMillis = 0L;
-
- // Ending timestamp of the collection cycle
- public long endTimeMillis = 0L;
-
- // Total time spent
- public long totalTimeUsedMillis = 0L;
-
- public AppUsageEntry(@NonNull AppUsageEntry other) {
- this.packageName = other.packageName;
- this.startTimeMillis = other.startTimeMillis;
- this.endTimeMillis = other.endTimeMillis;
- this.totalTimeUsedMillis = other.totalTimeUsedMillis;
- }
-
- public AppUsageEntry(@NonNull String packageName,
- @NonNull long startTimeMillis,
- @NonNull long endTimeMillis,
- @NonNull long totalTimeUsedMillis) {
- this.packageName = packageName;
- this.startTimeMillis = startTimeMillis;
- this.endTimeMillis = endTimeMillis;
- this.totalTimeUsedMillis = totalTimeUsedMillis;
- }
-}
diff --git a/src/com/android/ondevicepersonalization/services/data/user/LocationInfo.java b/src/com/android/ondevicepersonalization/services/data/user/LocationInfo.java
deleted file mode 100644
index a09bb1e..0000000
--- a/src/com/android/ondevicepersonalization/services/data/user/LocationInfo.java
+++ /dev/null
@@ -1,104 +0,0 @@
-/*
- * Copyright (C) 2022 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ondevicepersonalization.services.data.user;
-
-import androidx.annotation.NonNull;
-
-/** Location information. */
-public class LocationInfo {
- // Time in milliseconds.
- public long timeMillis = 0;
-
- // Latitude.
- public double latitude = 0;
-
- // Longitude.
- public double longitude = 0;
-
- // Location provider values.
- public enum LocationProvider {
- UNKNOWN,
- GPS,
- NETWORK;
-
- /**
- * The converter from ordinal to enum.
- * @param source the ordinal
- * @return enum
- */
- public static LocationProvider fromInteger(int source) {
- switch (source) {
- case 1:
- return GPS;
- case 2:
- return NETWORK;
- default:
- return UNKNOWN;
- }
- }
- };
-
- // Location provider.
- public LocationProvider provider = LocationProvider.UNKNOWN;
-
- // Whether the location source is precise.
- public boolean isPreciseLocation = false;
-
- public LocationInfo() { }
-
- // Deep copy constructor.
- public LocationInfo(@NonNull LocationInfo other) {
- this.timeMillis = other.timeMillis;
- this.latitude = other.latitude;
- this.longitude = other.longitude;
- this.provider = other.provider;
- this.isPreciseLocation = other.isPreciseLocation;
- }
-
- // Constructor for LocationInfo.
- public LocationInfo(@NonNull long timeMillis,
- @NonNull double latitude,
- @NonNull double longitude,
- @NonNull LocationProvider provider,
- @NonNull boolean isPrecise) {
- this.timeMillis = timeMillis;
- this.latitude = latitude;
- this.longitude = longitude;
- this.provider = provider;
- this.isPreciseLocation = isPrecise;
- }
-
- @Override
- public boolean equals(Object o) {
- if (o == this) {
- return true;
- }
- if (!(o instanceof LocationInfo)) {
- return false;
- }
- LocationInfo other = (LocationInfo) o;
- return this.latitude == other.latitude && this.longitude == other.longitude;
- }
-
- @Override
- public int hashCode() {
- int hash = 17;
- hash = hash * 31 + Double.valueOf(latitude).hashCode();
- hash = hash * 31 + Double.valueOf(longitude).hashCode();
- return hash;
- }
-}
diff --git a/src/com/android/ondevicepersonalization/services/data/user/RawUserData.java b/src/com/android/ondevicepersonalization/services/data/user/RawUserData.java
index 9ab50d0..0c0afb3 100644
--- a/src/com/android/ondevicepersonalization/services/data/user/RawUserData.java
+++ b/src/com/android/ondevicepersonalization/services/data/user/RawUserData.java
@@ -21,7 +21,6 @@
import android.net.NetworkCapabilities;
import java.util.ArrayList;
-import java.util.HashMap;
import java.util.List;
/**
@@ -53,18 +52,6 @@
// installed packages.
public List<AppInfo> appsInfo = new ArrayList<>();
- // A histogram of app usage: total times used per app in the last 30 days.
- public HashMap<String, Long> appUsageHistory = new HashMap<>();
-
- // User's most recently available location information.
- public LocationInfo currentLocation = new LocationInfo();
-
- /**
- * A histogram of location history: total time spent per location in the last 30 days.
- * Default precision level of locations is set to E4.
- */
- public HashMap<LocationInfo, Long> locationHistory = new HashMap<>();
-
private RawUserData() { }
/** Returns an instance of UserData. */
diff --git a/src/com/android/ondevicepersonalization/services/data/user/UserDataCollector.java b/src/com/android/ondevicepersonalization/services/data/user/UserDataCollector.java
index c6a04f8..9927f20 100644
--- a/src/com/android/ondevicepersonalization/services/data/user/UserDataCollector.java
+++ b/src/com/android/ondevicepersonalization/services/data/user/UserDataCollector.java
@@ -18,17 +18,12 @@
import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES;
-import android.app.usage.UsageStats;
-import android.app.usage.UsageStatsManager;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
-import android.database.Cursor;
-import android.location.Location;
-import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.NetworkCapabilities;
import android.os.BatteryManager;
@@ -40,14 +35,7 @@
import com.android.internal.annotations.VisibleForTesting;
import com.android.ondevicepersonalization.internal.util.LoggerFactory;
-import com.android.ondevicepersonalization.services.data.user.LocationInfo.LocationProvider;
-import java.util.ArrayDeque;
-import java.util.ArrayList;
-import java.util.Calendar;
-import java.util.Deque;
-import java.util.HashMap;
-import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Set;
@@ -98,33 +86,15 @@
@NonNull
private final TelephonyManager mTelephonyManager;
@NonNull final ConnectivityManager mConnectivityManager;
- @NonNull
- private final LocationManager mLocationManager;
- @NonNull
- private final UserDataDao mUserDataDao;
- // Metadata to keep track of the latest ending timestamp of app usage collection.
- @NonNull
- private long mLastTimeMillisAppUsageCollected;
- // Metadata to track the expired app usage entries, which are to be evicted.
- @NonNull
- private Deque<AppUsageEntry> mAllowedAppUsageEntries;
- // Metadata to track the expired location entries, which are to be evicted.
- @NonNull
- private Deque<LocationInfo> mAllowedLocationEntries;
// Metadata to track whether UserData has been initialized.
@NonNull
private boolean mInitialized;
- private UserDataCollector(Context context, UserDataDao userDataDao) {
+ private UserDataCollector(Context context) {
mContext = context;
mTelephonyManager = mContext.getSystemService(TelephonyManager.class);
mConnectivityManager = mContext.getSystemService(ConnectivityManager.class);
- mLocationManager = mContext.getSystemService(LocationManager.class);
- mUserDataDao = userDataDao;
- mLastTimeMillisAppUsageCollected = 0L;
- mAllowedAppUsageEntries = new ArrayDeque<>();
- mAllowedLocationEntries = new ArrayDeque<>();
mInitialized = false;
}
@@ -134,8 +104,7 @@
synchronized (UserDataCollector.class) {
if (sUserDataCollector == null) {
sUserDataCollector = new UserDataCollector(
- context.getApplicationContext(),
- UserDataDao.getInstance(context.getApplicationContext()));
+ context.getApplicationContext());
}
}
}
@@ -150,8 +119,7 @@
public static UserDataCollector getInstanceForTest(Context context) {
synchronized (UserDataCollector.class) {
if (sUserDataCollector == null) {
- sUserDataCollector = new UserDataCollector(context,
- UserDataDao.getInstanceForTest(context));
+ sUserDataCollector = new UserDataCollector(context);
}
return sUserDataCollector;
}
@@ -184,9 +152,6 @@
getDataNetworkType(userData);
getInstalledApps(userData.appsInfo);
- getAppUsageStats(userData.appUsageHistory);
- getLastknownLocation(userData.locationHistory, userData.currentLocation);
- getCurrentLocation(userData.locationHistory, userData.currentLocation);
}
/**
@@ -204,15 +169,6 @@
getInstalledApps(userData.appsInfo);
- recoverAppUsageHistogram(userData.appUsageHistory);
-
- getAppUsageStats(userData.appUsageHistory);
- // TODO (b/261748573): add non-trivial tests for location collection and histogram updates.
- recoverLocationHistogram(userData.locationHistory);
-
- getLastknownLocation(userData.locationHistory, userData.currentLocation);
-
- getCurrentLocation(userData.locationHistory, userData.currentLocation);
mInitialized = true;
}
@@ -356,216 +312,6 @@
}
/**
- * Get 24-hour app usage stats from [yesterday's midnight] to [tonight's midnight],
- * write them to database, and update the [appUsageHistory] histogram.
- * Skip the current collection cycle if yesterday's stats has been collected.
- */
- @VisibleForTesting
- public void getAppUsageStats(HashMap<String, Long> appUsageHistory) {
- try {
- Calendar cal = Calendar.getInstance();
- // Obtain the 24-hour query range between [yesterday midnight] and [today midnight].
- cal.set(Calendar.MILLISECOND, 0);
- cal.set(Calendar.SECOND, 0);
- cal.set(Calendar.MINUTE, 0);
- cal.set(Calendar.HOUR_OF_DAY, 0);
- final long endTimeMillis = cal.getTimeInMillis();
-
- // Skip the current collection cycle.
- if (endTimeMillis == mLastTimeMillisAppUsageCollected) {
- return;
- }
-
- // Collect yesterday's app usage stats.
- cal.add(Calendar.DATE, -1);
- final long startTimeMillis = cal.getTimeInMillis();
- UsageStatsManager usageStatsManager =
- mContext.getSystemService(UsageStatsManager.class);
- final List<UsageStats> statsList = usageStatsManager.queryUsageStats(
- UsageStatsManager.INTERVAL_BEST, startTimeMillis, endTimeMillis);
-
- List<AppUsageEntry> appUsageEntries = new ArrayList<>();
- for (UsageStats stats : statsList) {
- if (stats.getTotalTimeVisible() == 0) {
- continue;
- }
- appUsageEntries.add(new AppUsageEntry(stats.getPackageName(),
- startTimeMillis, endTimeMillis, stats.getTotalTimeVisible()));
- }
-
- // TODO(267678607): refactor the business logic when no stats is available.
- if (appUsageEntries.size() == 0) {
- return;
- }
-
- // Update database.
- if (!mUserDataDao.batchInsertAppUsageStatsData(appUsageEntries)) {
- return;
- }
- // Update in-memory histogram.
- updateAppUsageHistogram(appUsageHistory, appUsageEntries);
- // Update metadata if all steps succeed as a transaction.
- mLastTimeMillisAppUsageCollected = endTimeMillis;
- } catch (Exception e) {
- sLogger.w(TAG + ": Failed to collect app usage.");
- }
- }
-
- /**
- * Update histogram and handle TTL deletion for app usage (30 days).
- */
- private void updateAppUsageHistogram(HashMap<String, Long> appUsageHistory,
- List<AppUsageEntry> entries) {
- for (AppUsageEntry entry : entries) {
- mAllowedAppUsageEntries.add(entry);
- appUsageHistory.put(entry.packageName, appUsageHistory.getOrDefault(
- entry.packageName, 0L) + entry.totalTimeUsedMillis);
- }
- // Backtrack 30 days
- Calendar cal = Calendar.getInstance();
- cal.add(Calendar.DATE, -1 * UserDataDao.TTL_IN_MEMORY_DAYS);
- final long thresholdTimeMillis = cal.getTimeInMillis();
-
- // TTL deletion algorithm
- while (!mAllowedAppUsageEntries.isEmpty()
- && mAllowedAppUsageEntries.peekFirst().endTimeMillis < thresholdTimeMillis) {
- AppUsageEntry evictedEntry = mAllowedAppUsageEntries.removeFirst();
- if (appUsageHistory.containsKey(evictedEntry.packageName)) {
- final long updatedTotalTime = appUsageHistory.get(
- evictedEntry.packageName) - evictedEntry.totalTimeUsedMillis;
- if (updatedTotalTime == 0) {
- appUsageHistory.remove(evictedEntry.packageName);
- } else {
- appUsageHistory.put(evictedEntry.packageName, updatedTotalTime);
- }
- }
- }
- }
-
- /** Get last known location information. The result is immediate. */
- @VisibleForTesting
- public void getLastknownLocation(@NonNull HashMap<LocationInfo, Long> locationHistory,
- @NonNull LocationInfo locationInfo) {
- try {
- // TODO(b/290256559): Fix permissions issue.
- Location location = mLocationManager.getLastKnownLocation(
- LocationManager.FUSED_PROVIDER);
- if (location != null) {
- if (!setLocationInfo(location, locationInfo)) {
- return;
- }
- updateLocationHistogram(locationHistory, locationInfo);
- }
- } catch (Exception e) {
- // TODO(b/290256559): Fix permissions issue.
- sLogger.e(TAG + ": getLastKnownLocation() failed.", e);
- }
- }
-
- /** Get current location information. The result takes some time to generate. */
- @VisibleForTesting
- public void getCurrentLocation(@NonNull HashMap<LocationInfo, Long> locationHistory,
- @NonNull LocationInfo locationInfo) {
- try {
- // TODO(b/290256559): Fix permissions issue.
- String currentProvider = LocationManager.GPS_PROVIDER;
- if (mLocationManager.getProvider(currentProvider) == null) {
- currentProvider = LocationManager.FUSED_PROVIDER;
- }
- mLocationManager.getCurrentLocation(
- currentProvider,
- null,
- mContext.getMainExecutor(),
- location -> {
- if (location != null) {
- if (!setLocationInfo(location, locationInfo)) {
- return;
- }
- updateLocationHistogram(locationHistory, locationInfo);
- }
- }
- );
- } catch (Exception e) {
- sLogger.e(TAG + ": getCurrentLocation() failed.", e);
- }
- }
-
- /**
- * Persist collected location info and populate the in-memory current location.
- * The method should succeed or fail as a transaction to avoid discrepancies between
- * database and memory.
- *
- * @return true if location info collection is successful, false otherwise.
- */
- private boolean setLocationInfo(Location location, LocationInfo locationInfo) {
- long timeMillis = System.currentTimeMillis() - location.getElapsedRealtimeAgeMillis();
- double truncatedLatitude = Math.round(location.getLatitude() * 10000.0) / 10000.0;
- double truncatedLongitude = Math.round(location.getLongitude() * 10000.0) / 10000.0;
- LocationInfo.LocationProvider locationProvider = LocationProvider.UNKNOWN;
- boolean isPrecise = false;
-
- String provider = location.getProvider();
- if (LocationManager.GPS_PROVIDER.equals(provider)) {
- locationProvider = LocationInfo.LocationProvider.GPS;
- isPrecise = true;
- } else {
- if (LocationManager.NETWORK_PROVIDER.equals(provider)) {
- locationProvider = LocationInfo.LocationProvider.NETWORK;
- }
- }
-
- if (!mUserDataDao.insertLocationHistoryData(timeMillis, Double.toString(truncatedLatitude),
- Double.toString(truncatedLongitude), locationProvider.ordinal(), isPrecise)) {
- return false;
- }
- // update user's current location
- locationInfo.timeMillis = timeMillis;
- locationInfo.latitude = truncatedLatitude;
- locationInfo.longitude = truncatedLongitude;
- locationInfo.provider = locationProvider;
- locationInfo.isPreciseLocation = isPrecise;
- return true;
- }
-
- /**
- * Update histogram and handle TTL deletion for location history (30 days).
- */
- private void updateLocationHistogram(HashMap<LocationInfo, Long> locationHistory,
- LocationInfo newLocation) {
- LocationInfo curLocation = mAllowedLocationEntries.peekLast();
- // must be a deep copy
- mAllowedLocationEntries.add(new LocationInfo(newLocation));
- if (curLocation != null) {
- long durationMillis = newLocation.timeMillis - curLocation.timeMillis;
- locationHistory.put(curLocation,
- locationHistory.getOrDefault(curLocation, 0L) + durationMillis);
- }
-
- // Backtrack 30 days
- Calendar cal = Calendar.getInstance();
- cal.add(Calendar.DATE, -1 * UserDataDao.TTL_IN_MEMORY_DAYS);
- final long thresholdTimeMillis = cal.getTimeInMillis();
-
- // TTL deletion algorithm for locations
- while (!mAllowedLocationEntries.isEmpty()
- && mAllowedLocationEntries.peekFirst().timeMillis < thresholdTimeMillis) {
- LocationInfo evictedLocation = mAllowedLocationEntries.removeFirst();
- if (!mAllowedLocationEntries.isEmpty()) {
- long evictedDuration = mAllowedLocationEntries.peekFirst().timeMillis
- - evictedLocation.timeMillis;
- if (locationHistory.containsKey(evictedLocation)) {
- long updatedDuration = locationHistory.get(evictedLocation) - evictedDuration;
- if (updatedDuration == 0) {
- locationHistory.remove(evictedLocation);
- } else {
- locationHistory.put(evictedLocation, updatedDuration);
- }
- }
- }
- }
- }
-
- /**
* Util to reset all fields in [UserData] to default for testing purpose
*/
public void clearUserData(@NonNull RawUserData userData) {
@@ -576,8 +322,6 @@
userData.carrier = Carrier.UNKNOWN;
userData.networkCapabilities = null;
userData.appsInfo.clear();
- userData.appUsageHistory.clear();
- userData.locationHistory.clear();
}
/**
@@ -585,98 +329,6 @@
*/
public void clearMetadata() {
mInitialized = false;
- mLastTimeMillisAppUsageCollected = 0L;
- mAllowedAppUsageEntries = new ArrayDeque<>();
- mAllowedLocationEntries = new ArrayDeque<>();
- }
-
- /**
- * Reset app usage histogram and metadata in case of system crash.
- * Only used during initial data collection.
- */
- @VisibleForTesting
- public void recoverAppUsageHistogram(HashMap<String, Long> appUsageHistory) {
- Cursor cursor = mUserDataDao.readAppUsageInLastXDays(UserDataDao.TTL_IN_MEMORY_DAYS);
- if (cursor == null) {
- return;
- }
- // Metadata to be reset.
- appUsageHistory.clear();
- mLastTimeMillisAppUsageCollected = 0L;
- mAllowedAppUsageEntries.clear();
-
- if (cursor.moveToFirst()) {
- while (!cursor.isAfterLast()) {
- String packageName = cursor.getString(cursor.getColumnIndex(
- UserDataTables.AppUsageHistory.PACKAGE_NAME));
- long startTimeMillis = cursor.getLong(cursor.getColumnIndex(
- UserDataTables.AppUsageHistory.STARTING_TIME_SEC));
- long endTimeMillis = cursor.getLong(cursor.getColumnIndex(
- UserDataTables.AppUsageHistory.ENDING_TIME_SEC));
- long totalTimeUsedMillis = cursor.getLong(cursor.getColumnIndex(
- UserDataTables.AppUsageHistory.TOTAL_TIME_USED_SEC));
- mAllowedAppUsageEntries.add(new AppUsageEntry(packageName,
- startTimeMillis, endTimeMillis, totalTimeUsedMillis));
- appUsageHistory.put(packageName, appUsageHistory.getOrDefault(packageName,
- 0L) + totalTimeUsedMillis);
- cursor.moveToNext();
- }
- }
-
- if (cursor.moveToLast()) {
- mLastTimeMillisAppUsageCollected = cursor.getLong(cursor.getColumnIndex(
- UserDataTables.AppUsageHistory.ENDING_TIME_SEC));
- }
- }
-
- /**
- * Reset location histogram and metadata in case of system crash.
- */
- @VisibleForTesting
- public void recoverLocationHistogram(HashMap<LocationInfo, Long> locationHistory) {
- Cursor cursor = mUserDataDao.readLocationInLastXDays(mUserDataDao.TTL_IN_MEMORY_DAYS);
- if (cursor == null) {
- return;
- }
- // Metadata to be reset.
- locationHistory.clear();
- mAllowedLocationEntries.clear();
-
- if (cursor.moveToFirst()) {
- while (!cursor.isAfterLast()) {
- long timeMillis = cursor.getLong(cursor.getColumnIndex(
- UserDataTables.LocationHistory.TIME_SEC));
- String latitude = cursor.getString(cursor.getColumnIndex(
- UserDataTables.LocationHistory.LATITUDE));
- String longitude = cursor.getString(cursor.getColumnIndex(
- UserDataTables.LocationHistory.LONGITUDE));
- int source = cursor.getInt(cursor.getColumnIndex(
- UserDataTables.LocationHistory.SOURCE));
- boolean isPrecise = cursor.getInt(cursor.getColumnIndex(
- UserDataTables.LocationHistory.IS_PRECISE)) > 0;
- mAllowedLocationEntries.add(new LocationInfo(timeMillis,
- Double.parseDouble(latitude),
- Double.parseDouble(longitude),
- LocationProvider.fromInteger(source),
- isPrecise));
- cursor.moveToNext();
- }
- }
-
- Iterator<LocationInfo> iterator = mAllowedLocationEntries.iterator();
- while (iterator.hasNext()) {
- LocationInfo currentLocation = iterator.next();
- if (!iterator.hasNext()) {
- return;
- }
- LocationInfo nextLocation = iterator.next();
- final long duration = nextLocation.timeMillis - currentLocation.timeMillis;
- if (duration < 0) {
- sLogger.v(TAG + ": LocationInfo entries are retrieved with wrong order.");
- }
- locationHistory.put(currentLocation,
- locationHistory.getOrDefault(currentLocation, 0L) + duration);
- }
}
@VisibleForTesting
@@ -685,21 +337,6 @@
}
@VisibleForTesting
- public long getLastTimeMillisAppUsageCollected() {
- return mLastTimeMillisAppUsageCollected;
- }
-
- @VisibleForTesting
- public Deque<AppUsageEntry> getAllowedAppUsageEntries() {
- return mAllowedAppUsageEntries;
- }
-
- @VisibleForTesting
- public Deque<LocationInfo> getAllowedLocationEntries() {
- return mAllowedLocationEntries;
- }
-
- @VisibleForTesting
static NetworkCapabilities getFilteredNetworkCapabilities(
NetworkCapabilities networkCapabilities) {
NetworkCapabilities.Builder builder =
@@ -714,11 +351,4 @@
}
return builder.build();
}
-
- /**
- * Clear all user data in database for testing purpose.
- */
- public void clearDatabase() {
- mUserDataDao.clearUserData();
- }
}
diff --git a/src/com/android/ondevicepersonalization/services/data/user/UserDataDao.java b/src/com/android/ondevicepersonalization/services/data/user/UserDataDao.java
deleted file mode 100644
index 361e688..0000000
--- a/src/com/android/ondevicepersonalization/services/data/user/UserDataDao.java
+++ /dev/null
@@ -1,241 +0,0 @@
-/*
- * Copyright (C) 2022 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ondevicepersonalization.services.data.user;
-
-import android.content.ContentValues;
-import android.content.Context;
-import android.database.Cursor;
-import android.database.sqlite.SQLiteDatabase;
-import android.database.sqlite.SQLiteException;
-
-
-import com.android.internal.annotations.VisibleForTesting;
-import com.android.ondevicepersonalization.internal.util.LoggerFactory;
-import com.android.ondevicepersonalization.services.data.OnDevicePersonalizationDbHelper;
-
-import java.util.Calendar;
-import java.util.List;
-
-/** DAO for accessing to vendor data tables. */
-public class UserDataDao {
- private static final LoggerFactory.Logger sLogger = LoggerFactory.getLogger();
- private static final String TAG = "UserDataDao";
-
- private static volatile UserDataDao sUserDataDao;
- private final OnDevicePersonalizationDbHelper mDbHelper;
- public static final int TTL_IN_MEMORY_DAYS = 30;
-
- private UserDataDao(OnDevicePersonalizationDbHelper dbHelper) {
- this.mDbHelper = dbHelper;
- }
-
- /**
- * Returns an instance of the UserDataDao given a context.
- *
- * @param context The context of the application.
- * @return Instance of UserDataDao for accessing the requested package's table.
- */
- public static UserDataDao getInstance(Context context) {
- if (sUserDataDao == null) {
- synchronized (UserDataDao.class) {
- if (sUserDataDao == null) {
- sUserDataDao = new UserDataDao(
- OnDevicePersonalizationDbHelper.getInstance(
- context.getApplicationContext()));
- }
- }
- }
- return sUserDataDao;
- }
-
- /**
- * Returns an instance of the UserDataDao given a context. This is used for testing only.
- */
- @VisibleForTesting
- public static UserDataDao getInstanceForTest(Context context) {
- synchronized (UserDataDao.class) {
- if (sUserDataDao == null) {
- sUserDataDao = new UserDataDao(
- OnDevicePersonalizationDbHelper.getInstanceForTest(context));
- }
- return sUserDataDao;
- }
- }
-
- /**
- * Inserts location history row if it doesn't already exist.
- *
- * @return true if the insert succeeded, false otherwise.
- */
- public boolean insertLocationHistoryData(long timeSec, String latitude, String longitude,
- int source, boolean isPrecise) {
- try {
- SQLiteDatabase db = mDbHelper.getWritableDatabase();
- if (db == null) {
- return false;
- }
- ContentValues values = new ContentValues();
- values.put(UserDataTables.LocationHistory.TIME_SEC, timeSec);
- values.put(UserDataTables.LocationHistory.LATITUDE, latitude);
- values.put(UserDataTables.LocationHistory.LONGITUDE, longitude);
- values.put(UserDataTables.LocationHistory.SOURCE, source);
- values.put(UserDataTables.LocationHistory.IS_PRECISE, isPrecise);
- return db.insertWithOnConflict(UserDataTables.LocationHistory.TABLE_NAME, null, values,
- SQLiteDatabase.CONFLICT_REPLACE) != -1;
- } catch (SQLiteException e) {
- sLogger.e(TAG + ": Failed to insert location history data", e);
- return false;
- }
- }
-
- /**
- * Inserts a single app usage history entry.
- *
- * @return true if the insert succeeded, false otherwise.
- */
- public boolean insertAppUsageStatsData(String packageName, long startingTimeSec,
- long endingTimeSec, long totalTimeUsedSec) {
- try {
- SQLiteDatabase db = mDbHelper.getWritableDatabase();
- ContentValues values = new ContentValues();
- values.put(UserDataTables.AppUsageHistory.PACKAGE_NAME, packageName);
- values.put(UserDataTables.AppUsageHistory.STARTING_TIME_SEC, startingTimeSec);
- values.put(UserDataTables.AppUsageHistory.ENDING_TIME_SEC, endingTimeSec);
- values.put(UserDataTables.AppUsageHistory.TOTAL_TIME_USED_SEC, totalTimeUsedSec);
- return db.insertWithOnConflict(UserDataTables.AppUsageHistory.TABLE_NAME, null, values,
- SQLiteDatabase.CONFLICT_REPLACE) != -1;
- } catch (SQLiteException e) {
- sLogger.e(TAG + ": Failed to insert app usage history data", e);
- return false;
- }
- }
-
- /**
- * Batch inserts a list of [UsageStats].
- * @return true if all insertions succeed as a transaction, false otherwise.
- */
- public boolean batchInsertAppUsageStatsData(List<AppUsageEntry> appUsageEntries) {
- SQLiteDatabase db = mDbHelper.getWritableDatabase();
- if (db == null) {
- return false;
- }
- try {
- db.beginTransaction();
- for (AppUsageEntry entry : appUsageEntries) {
- if (!insertAppUsageStatsData(entry.packageName, entry.startTimeMillis,
- entry.endTimeMillis, entry.totalTimeUsedMillis)) {
- return false;
- }
- }
- db.setTransactionSuccessful();
- } finally {
- db.endTransaction();
- }
- return true;
- }
-
- /**
- * Read all app usage rows collected in the last x days.
- * @return
- */
- public Cursor readAppUsageInLastXDays(int dayCount) {
- if (dayCount > TTL_IN_MEMORY_DAYS) {
- sLogger.e(TAG + ": Illegal attempt to read " + dayCount + " rows, which is more than "
- + TTL_IN_MEMORY_DAYS + " days");
- return null;
- }
- Calendar cal = Calendar.getInstance();
- cal.add(Calendar.DATE, -1 * dayCount);
- final long thresholdTimeMillis = cal.getTimeInMillis();
- try {
- SQLiteDatabase db = mDbHelper.getReadableDatabase();
- String[] columns = new String[]{UserDataTables.AppUsageHistory.PACKAGE_NAME,
- UserDataTables.AppUsageHistory.STARTING_TIME_SEC,
- UserDataTables.AppUsageHistory.ENDING_TIME_SEC,
- UserDataTables.AppUsageHistory.TOTAL_TIME_USED_SEC};
- String selection = UserDataTables.AppUsageHistory.ENDING_TIME_SEC + " >= ?";
- String[] selectionArgs = new String[]{String.valueOf(thresholdTimeMillis)};
- String orderBy = UserDataTables.AppUsageHistory.ENDING_TIME_SEC;
- return db.query(
- UserDataTables.AppUsageHistory.TABLE_NAME,
- columns,
- selection,
- selectionArgs,
- null,
- null,
- orderBy
- );
- } catch (SQLiteException e) {
- sLogger.e(TAG + ": Failed to read " + UserDataTables.AppUsageHistory.TABLE_NAME
- + " in the last " + dayCount + " days" , e);
- }
- return null;
- }
-
- /**
- * Return all location rows collected in the last X days.
- * @return
- */
- public Cursor readLocationInLastXDays(int dayCount) {
- if (dayCount > TTL_IN_MEMORY_DAYS) {
- sLogger.e(TAG + ": Illegal attempt to read " + dayCount + " rows, which is more than "
- + TTL_IN_MEMORY_DAYS + " days");
- return null;
- }
- Calendar cal = Calendar.getInstance();
- cal.add(Calendar.DATE, -1 * dayCount);
- final long thresholdTimeMillis = cal.getTimeInMillis();
- try {
- SQLiteDatabase db = mDbHelper.getReadableDatabase();
- String[] columns = new String[]{UserDataTables.LocationHistory.TIME_SEC,
- UserDataTables.LocationHistory.LATITUDE,
- UserDataTables.LocationHistory.LONGITUDE,
- UserDataTables.LocationHistory.SOURCE,
- UserDataTables.LocationHistory.IS_PRECISE};
- String selection = UserDataTables.LocationHistory.TIME_SEC + " >= ?";
- String[] selectionArgs = new String[]{String.valueOf(thresholdTimeMillis)};
- String orderBy = UserDataTables.LocationHistory.TIME_SEC;
- return db.query(
- UserDataTables.LocationHistory.TABLE_NAME,
- columns,
- selection,
- selectionArgs,
- null,
- null,
- orderBy
- );
- } catch (SQLiteException e) {
- sLogger.e(TAG + ": Failed to read " + UserDataTables.LocationHistory.TABLE_NAME
- + " in the last " + dayCount + " days" , e);
- }
- return null;
- }
-
- /**
- * Clear all records in user data tables.
- * @return true if succeed, false otherwise.
- */
- public boolean clearUserData() {
- SQLiteDatabase db = mDbHelper.getWritableDatabase();
- if (db == null) {
- return false;
- }
- db.delete(UserDataTables.AppUsageHistory.TABLE_NAME, null, null);
- db.delete(UserDataTables.LocationHistory.TABLE_NAME, null, null);
- return true;
- }
-}
diff --git a/src/com/android/ondevicepersonalization/services/data/user/UserDataTables.java b/src/com/android/ondevicepersonalization/services/data/user/UserDataTables.java
deleted file mode 100644
index 8a5d227..0000000
--- a/src/com/android/ondevicepersonalization/services/data/user/UserDataTables.java
+++ /dev/null
@@ -1,123 +0,0 @@
-/*
- * Copyright (C) 2022 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ondevicepersonalization.services.data.user;
-
-import android.provider.BaseColumns;
-
-/** Container class for definitions and constants of user data tables. */
-public final class UserDataTables implements BaseColumns {
- public static final String USER_TABLE_PREFIX = "user_";
- public static final String INDEX_PREFIX = "index_";
-
- /** Location history table. */
- public static class LocationHistory implements BaseColumns {
- /** The name of location history table. */
- public static final String TABLE_NAME = USER_TABLE_PREFIX + "location_history";
-
- /** The name of location history index. */
- public static final String INDEX_NAME = INDEX_PREFIX + TABLE_NAME;
-
- /** The time that the location is retrieved in seconds. */
- public static final String TIME_SEC = "time_sec";
-
- /** The latitude of the location in the format of "[+-]DDD.DDDDD". */
- public static final String LATITUDE = "latitude";
-
- /** The Longitude of the location in the format of "[+-]DDD.DDDDD". */
- public static final String LONGITUDE = "longitude";
-
- /** The source of location signal. */
- public static final String SOURCE = "source";
-
- /** Is the location accuracy precise or coarse. */
- public static final String IS_PRECISE = "is_precise";
-
- public static final String CREATE_TABLE_STATEMENT = "CREATE TABLE IF NOT EXISTS "
- + TABLE_NAME + " ("
- + _ID + " INTEGER PRIMARY KEY, "
- + TIME_SEC + " INTEGER NOT NULL, "
- + LATITUDE + " TEXT NOT NULL, "
- + LONGITUDE + " TEXT NOT NULL, "
- + SOURCE + " INTEGER NOT NULL, "
- + IS_PRECISE + " INTEGER NOT NULL)";
-
- public static final String CREATE_INDEXES_STATEMENT = "CREATE INDEX IF NOT EXISTS "
- + INDEX_NAME + " ON "
- + TABLE_NAME + "("
- + TIME_SEC + ")";
- }
-
- /** App usage stats history table. */
- public static class AppUsageHistory implements BaseColumns {
- /** The name of app usage stats table. */
- public static final String TABLE_NAME = USER_TABLE_PREFIX + "app_usage_history";
-
- /** The package/app name of a usage activity. */
- public static final String PACKAGE_NAME = "package_name";
-
- /** Activity starting time of the app in seconds. */
- public static final String STARTING_TIME_SEC = "starting_time_sec";
-
- /** Activity ending time of the app in seconds. */
- public static final String ENDING_TIME_SEC = "ending_time_sec";
-
- /** Total activity time (on the foreground) of the app in seconds. */
- public static final String TOTAL_TIME_USED_SEC = "total_time_used_sec";
-
- /** The index name of app usage stats table based on starting timestamp. */
- public static final String STARTING_TIME_SEC_INDEX_NAME = INDEX_PREFIX
- + TABLE_NAME + STARTING_TIME_SEC;
-
- /** The index name of app usage stats table based on ending timestamp. */
- public static final String ENDING_TIME_SEC_INDEX_NAME = INDEX_PREFIX
- + TABLE_NAME + ENDING_TIME_SEC;
-
- /** The index name of app usage stats table based on total time spent. */
- public static final String TOTAL_TIME_USED_SEC_INDEX_NAME = INDEX_PREFIX
- + TABLE_NAME + TOTAL_TIME_USED_SEC;
-
- public static final String CREATE_TABLE_STATEMENT = "CREATE TABLE IF NOT EXISTS "
- + TABLE_NAME + " ("
- + _ID + " INTEGER PRIMARY KEY, "
- + PACKAGE_NAME + " TEXT NOT NULL, "
- + STARTING_TIME_SEC + " INTEGER NOT NULL, "
- + ENDING_TIME_SEC + " INTEGER NOT NULL, "
- + TOTAL_TIME_USED_SEC + " INTEGER NOT NULL)";
-
- // All timestamp-related fields could be of interests of FA queries.
- public static final String CREATE_STARTING_TIME_SEC_INDEX_STATEMENT =
- "CREATE INDEX IF NOT EXISTS "
- + STARTING_TIME_SEC_INDEX_NAME + " ON "
- + TABLE_NAME + "("
- + STARTING_TIME_SEC + ")";
-
- public static final String CREATE_ENDING_TIME_SEC_INDEX_STATEMENT =
- "CREATE INDEX IF NOT EXISTS "
- + ENDING_TIME_SEC_INDEX_NAME + " ON "
- + TABLE_NAME + "("
- + ENDING_TIME_SEC + ")";
-
- public static final String CREATE_TOTAL_TIME_USED_SEC_INDEX_STATEMENT =
- "CREATE INDEX IF NOT EXISTS "
- + TOTAL_TIME_USED_SEC_INDEX_NAME + " ON "
- + TABLE_NAME + "("
- + TOTAL_TIME_USED_SEC + ")";
- }
-
- // Private constructor to prevent instantiation.
- private UserDataTables() {}
-}
diff --git a/tests/servicetests/src/com/android/ondevicepersonalization/services/OnDevicePersonalizationConfigServiceTest.java b/tests/servicetests/src/com/android/ondevicepersonalization/services/OnDevicePersonalizationConfigServiceTest.java
index 87d0c62..cb73fa7 100644
--- a/tests/servicetests/src/com/android/ondevicepersonalization/services/OnDevicePersonalizationConfigServiceTest.java
+++ b/tests/servicetests/src/com/android/ondevicepersonalization/services/OnDevicePersonalizationConfigServiceTest.java
@@ -19,7 +19,6 @@
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotEquals;
-import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertThrows;
import static org.junit.Assert.assertTrue;
import static org.mockito.ArgumentMatchers.anyString;
@@ -30,7 +29,6 @@
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
-import android.database.Cursor;
import android.os.IBinder;
import androidx.test.core.app.ApplicationProvider;
@@ -38,7 +36,6 @@
import com.android.ondevicepersonalization.services.data.user.RawUserData;
import com.android.ondevicepersonalization.services.data.user.UserDataCollector;
-import com.android.ondevicepersonalization.services.data.user.UserDataDao;
import com.android.ondevicepersonalization.services.data.user.UserPrivacyStatus;
import org.junit.After;
@@ -61,7 +58,6 @@
private UserPrivacyStatus mUserPrivacyStatus;
private RawUserData mUserData;
private UserDataCollector mUserDataCollector;
- private UserDataDao mUserDataDao;
@Before
public void setup() throws Exception {
@@ -77,7 +73,6 @@
TimeZone pstTime = TimeZone.getTimeZone("GMT-08:00");
TimeZone.setDefault(pstTime);
mUserDataCollector = UserDataCollector.getInstanceForTest(mContext);
- mUserDataDao = UserDataDao.getInstanceForTest(mContext);
}
@Test
@@ -129,12 +124,6 @@
assertEquals(0, mUserData.utcOffset);
assertFalse(mUserDataCollector.isInitialized());
- Cursor appUsageCursor = mUserDataDao.readAppUsageInLastXDays(30);
- assertNotNull(appUsageCursor);
- assertEquals(0, appUsageCursor.getCount());
- Cursor locationCursor = mUserDataDao.readLocationInLastXDays(30);
- assertNotNull(locationCursor);
- assertEquals(0, locationCursor.getCount());
}
@Test
@@ -152,14 +141,6 @@
assertNotEquals(0, mUserData.utcOffset);
int utcOffset = mUserData.utcOffset;
assertTrue(mUserDataCollector.isInitialized());
- Cursor appUsageCursor = mUserDataDao.readAppUsageInLastXDays(30);
- Cursor locationCursor = mUserDataDao.readLocationInLastXDays(30);
- assertNotNull(appUsageCursor);
- assertNotNull(locationCursor);
- int appUsageCount = appUsageCursor.getCount();
- int locationCount = locationCursor.getCount();
- assertTrue(appUsageCount > 0);
- assertTrue(locationCount > 0);
CountDownLatch latch = new CountDownLatch(1);
mBinder.setPersonalizationStatus(true,
@@ -181,12 +162,6 @@
// Adult data should not be roll-back'ed
assertEquals(utcOffset, mUserData.utcOffset);
assertTrue(mUserDataCollector.isInitialized());
- Cursor newAppUsageCursor = mUserDataDao.readAppUsageInLastXDays(30);
- Cursor newLocationCursor = mUserDataDao.readLocationInLastXDays(30);
- assertNotNull(newAppUsageCursor);
- assertNotNull(newLocationCursor);
- assertEquals(appUsageCount, newAppUsageCursor.getCount());
- assertEquals(locationCount, newLocationCursor.getCount());
}
@Test
@@ -201,15 +176,9 @@
public void tearDown() throws Exception {
mUserDataCollector.clearUserData(mUserData);
mUserDataCollector.clearMetadata();
- mUserDataCollector.clearDatabase();
}
private void populateUserData() {
mUserDataCollector.updateUserData(mUserData);
- // Populate the database in case that no records are collected by UserDataCollector.
- long currentTimeMillis = System.currentTimeMillis();
- mUserDataDao.insertAppUsageStatsData("testApp", 0, currentTimeMillis, 0);
- mUserDataDao.insertLocationHistoryData(currentTimeMillis,
- "111.11111", "-222.22222", 1, true);
}
}
diff --git a/tests/servicetests/src/com/android/ondevicepersonalization/services/data/OnDevicePersonalizationDbHelperTest.java b/tests/servicetests/src/com/android/ondevicepersonalization/services/data/OnDevicePersonalizationDbHelperTest.java
index 2c5885f..cbb6873 100644
--- a/tests/servicetests/src/com/android/ondevicepersonalization/services/data/OnDevicePersonalizationDbHelperTest.java
+++ b/tests/servicetests/src/com/android/ondevicepersonalization/services/data/OnDevicePersonalizationDbHelperTest.java
@@ -29,7 +29,6 @@
import com.android.ondevicepersonalization.services.data.events.EventStateContract;
import com.android.ondevicepersonalization.services.data.events.EventsContract;
import com.android.ondevicepersonalization.services.data.events.QueriesContract;
-import com.android.ondevicepersonalization.services.data.user.UserDataTables;
import com.android.ondevicepersonalization.services.data.vendor.VendorSettingsContract;
import org.junit.Before;
@@ -56,14 +55,6 @@
assertTrue(hasEntity(QueriesContract.QueriesEntry.TABLE_NAME, "table"));
assertTrue(hasEntity(EventsContract.EventsEntry.TABLE_NAME, "table"));
assertTrue(hasEntity(EventStateContract.EventStateEntry.TABLE_NAME, "table"));
- assertTrue(hasEntity(UserDataTables.LocationHistory.TABLE_NAME, "table"));
- assertTrue(hasEntity(UserDataTables.LocationHistory.INDEX_NAME, "index"));
- assertTrue(hasEntity(UserDataTables.AppUsageHistory.TABLE_NAME, "table"));
- assertTrue(hasEntity(
- UserDataTables.AppUsageHistory.STARTING_TIME_SEC_INDEX_NAME, "index"));
- assertTrue(hasEntity(UserDataTables.AppUsageHistory.ENDING_TIME_SEC_INDEX_NAME, "index"));
- assertTrue(hasEntity(
- UserDataTables.AppUsageHistory.TOTAL_TIME_USED_SEC_INDEX_NAME, "index"));
}
@Test
diff --git a/tests/servicetests/src/com/android/ondevicepersonalization/services/data/user/UserDataCollectionJobServiceTest.java b/tests/servicetests/src/com/android/ondevicepersonalization/services/data/user/UserDataCollectionJobServiceTest.java
index d38ec16..e3c8551 100644
--- a/tests/servicetests/src/com/android/ondevicepersonalization/services/data/user/UserDataCollectionJobServiceTest.java
+++ b/tests/servicetests/src/com/android/ondevicepersonalization/services/data/user/UserDataCollectionJobServiceTest.java
@@ -37,7 +37,6 @@
import com.android.ondevicepersonalization.services.OnDevicePersonalizationConfig;
import com.android.ondevicepersonalization.services.OnDevicePersonalizationExecutors;
import com.android.ondevicepersonalization.services.PhFlagsTestUtil;
-import com.android.ondevicepersonalization.services.data.OnDevicePersonalizationDbHelper;
import com.google.common.util.concurrent.MoreExecutors;
@@ -139,11 +138,5 @@
public void cleanUp() {
mUserDataCollector.clearUserData(RawUserData.getInstance());
mUserDataCollector.clearMetadata();
- mUserDataCollector.clearDatabase();
- OnDevicePersonalizationDbHelper dbHelper =
- OnDevicePersonalizationDbHelper.getInstanceForTest(mContext);
- dbHelper.getWritableDatabase().close();
- dbHelper.getReadableDatabase().close();
- dbHelper.close();
}
}
diff --git a/tests/servicetests/src/com/android/ondevicepersonalization/services/data/user/UserDataCollectorTest.java b/tests/servicetests/src/com/android/ondevicepersonalization/services/data/user/UserDataCollectorTest.java
index 13588c4..a2b6c9b 100644
--- a/tests/servicetests/src/com/android/ondevicepersonalization/services/data/user/UserDataCollectorTest.java
+++ b/tests/servicetests/src/com/android/ondevicepersonalization/services/data/user/UserDataCollectorTest.java
@@ -36,10 +36,7 @@
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
-import java.util.ArrayDeque;
import java.util.ArrayList;
-import java.util.Deque;
-import java.util.HashMap;
import java.util.List;
import java.util.TimeZone;
@@ -109,82 +106,9 @@
filteredCap.getCapabilities());
}
- @Test
- public void testRecoveryFromSystemCrash() {
- mCollector.updateUserData(mUserData);
- // Backup sample answer.
- final HashMap<String, Long> refAppUsageHistogram =
- copyAppUsageMap(mUserData.appUsageHistory);
- final HashMap<LocationInfo, Long> refLocationHistogram =
- copyLocationMap(mUserData.locationHistory);
- final Deque<AppUsageEntry> refAllowedAppUsageEntries =
- copyAppUsageEntries(mCollector.getAllowedAppUsageEntries());
- final Deque<LocationInfo> refAllowedLocationEntries =
- copyLocationEntries(mCollector.getAllowedLocationEntries());
- final long refLastTimeAppUsageCollected = mCollector.getLastTimeMillisAppUsageCollected();
-
- // Mock system crash scenario.
- mCollector.clearUserData(mUserData);
- mCollector.clearMetadata();
- mCollector.recoverAppUsageHistogram(mUserData.appUsageHistory);
- mCollector.recoverLocationHistogram(mUserData.locationHistory);
-
- assertEquals(refAppUsageHistogram.size(), mUserData.appUsageHistory.size());
- for (String key: refAppUsageHistogram.keySet()) {
- assertTrue(mUserData.appUsageHistory.containsKey(key));
- assertEquals(refAppUsageHistogram.get(key), mUserData.appUsageHistory.get(key));
- }
- assertEquals(refLastTimeAppUsageCollected,
- mCollector.getLastTimeMillisAppUsageCollected());
- assertEquals(refAllowedAppUsageEntries.size(),
- mCollector.getAllowedAppUsageEntries().size());
-
- assertEquals(refLocationHistogram.size(), mUserData.locationHistory.size());
- for (LocationInfo locationInfo: refLocationHistogram.keySet()) {
- assertTrue(mUserData.locationHistory.containsKey(locationInfo));
- assertEquals(refLocationHistogram.get(locationInfo),
- mUserData.locationHistory.get(locationInfo));
- }
- assertEquals(refAllowedLocationEntries.size(),
- mCollector.getAllowedLocationEntries().size());
- }
-
- private HashMap<String, Long> copyAppUsageMap(HashMap<String, Long> other) {
- HashMap<String, Long> copy = new HashMap<>();
- for (String key: other.keySet()) {
- copy.put(key, (long) other.get(key));
- }
- return copy;
- }
-
- private HashMap<LocationInfo, Long> copyLocationMap(HashMap<LocationInfo, Long> other) {
- HashMap<LocationInfo, Long> copy = new HashMap<>();
- for (LocationInfo key: other.keySet()) {
- copy.put(new LocationInfo(key), (long) other.get(key));
- }
- return copy;
- }
-
- private Deque<AppUsageEntry> copyAppUsageEntries(Deque<AppUsageEntry> other) {
- Deque<AppUsageEntry> copy = new ArrayDeque<>();
- for (AppUsageEntry entry: other) {
- copy.add(new AppUsageEntry(entry));
- }
- return copy;
- }
-
- private Deque<LocationInfo> copyLocationEntries(Deque<LocationInfo> other) {
- Deque<LocationInfo> copy = new ArrayDeque<>();
- for (LocationInfo entry: other) {
- copy.add(new LocationInfo(entry));
- }
- return copy;
- }
-
@After
public void cleanUp() {
mCollector.clearUserData(mUserData);
mCollector.clearMetadata();
- mCollector.clearDatabase();
}
}
diff --git a/tests/servicetests/src/com/android/ondevicepersonalization/services/data/user/UserDataDaoTest.java b/tests/servicetests/src/com/android/ondevicepersonalization/services/data/user/UserDataDaoTest.java
deleted file mode 100644
index 25b1ad6..0000000
--- a/tests/servicetests/src/com/android/ondevicepersonalization/services/data/user/UserDataDaoTest.java
+++ /dev/null
@@ -1,161 +0,0 @@
-/*
- * Copyright (C) 2022 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ondevicepersonalization.services.data.user;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertTrue;
-
-import android.content.Context;
-import android.database.Cursor;
-
-import androidx.test.core.app.ApplicationProvider;
-
-import com.android.ondevicepersonalization.services.data.OnDevicePersonalizationDbHelper;
-
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.junit.runners.JUnit4;
-
-import java.util.Calendar;
-
-@RunWith(JUnit4.class)
-public class UserDataDaoTest {
- private final Context mContext = ApplicationProvider.getApplicationContext();
- private UserDataDao mDao;
- private static final int TEST_LEGAL_DAYS = 28;
- private static final int TEST_ILLEGAL_DAYS = 32;
- private static final int TEST_TOTAL_TIMES = 60;
- private static final long MILLISECONDS_PER_DAY = 86400000;
- private static final String TEST_PACKAGE_NAME = "foobar";
- private static final long TEST_TOTAL_TIME_PER_DAY = 100;
- private static final String TEST_LATITUDE = "100.1111";
- private static final String TEST_LONGITUDE = "200.1111";
-
- @Before
- public void setup() {
- mDao = UserDataDao.getInstanceForTest(mContext);
- }
-
- @Test
- public void testInsert() {
- boolean insertResult = mDao.insertLocationHistoryData(
- 1234567890, "111.11111", "-222.22222", 1, true);
- assertTrue(insertResult);
- assertTrue(mDao.insertAppUsageStatsData("TikTok", 999100, 999200, 100));
- }
-
- @Test
- public void testInsertNullLatitude() {
- boolean insertResult = mDao.insertLocationHistoryData(
- 1234567890, null, "-222.22222", 1, true);
- assertFalse(insertResult);
- }
-
- @Test
- public void testInsertNullLongitude() {
- boolean insertResult = mDao.insertLocationHistoryData(
- 1234567890, "111.11111", null, 1, true);
- assertFalse(insertResult);
- }
-
- @Test
- public void testReadAppUsageStats() {
- Calendar cal = Calendar.getInstance();
- cal.set(Calendar.MILLISECOND, 0);
- cal.set(Calendar.SECOND, 0);
- cal.set(Calendar.MINUTE, 0);
- cal.set(Calendar.HOUR_OF_DAY, 0);
- long endTimeMillis = cal.getTimeInMillis();
- long refTimeMillis = endTimeMillis - (TEST_LEGAL_DAYS - 1) * MILLISECONDS_PER_DAY;
- for (int i = 0; i < TEST_TOTAL_TIMES; ++i) {
- final long startTimeMillis = endTimeMillis - MILLISECONDS_PER_DAY;
- mDao.insertAppUsageStatsData(TEST_PACKAGE_NAME,
- startTimeMillis, endTimeMillis, TEST_TOTAL_TIME_PER_DAY);
- endTimeMillis = startTimeMillis;
- }
- Cursor cursor = mDao.readAppUsageInLastXDays(TEST_LEGAL_DAYS);
- assertNotNull(cursor);
- assertEquals(TEST_LEGAL_DAYS, cursor.getCount());
- if (cursor.moveToFirst()) {
- while (!cursor.isAfterLast()) {
- assertEquals(TEST_PACKAGE_NAME, cursor.getString(cursor.getColumnIndex(
- UserDataTables.AppUsageHistory.PACKAGE_NAME)));
- assertEquals(refTimeMillis - MILLISECONDS_PER_DAY, cursor.getLong(
- cursor.getColumnIndex(UserDataTables.AppUsageHistory.STARTING_TIME_SEC)));
- assertEquals(refTimeMillis, cursor.getLong(cursor.getColumnIndex(
- UserDataTables.AppUsageHistory.ENDING_TIME_SEC)));
- assertEquals(TEST_TOTAL_TIME_PER_DAY, cursor.getLong(cursor.getColumnIndex(
- UserDataTables.AppUsageHistory.TOTAL_TIME_USED_SEC)));
- cursor.moveToNext();
- refTimeMillis += MILLISECONDS_PER_DAY;
- }
- }
-
- cursor = mDao.readAppUsageInLastXDays(TEST_ILLEGAL_DAYS);
- assertNull(cursor);
- }
-
- @Test
- public void testReadLocationInfo() {
- Calendar cal = Calendar.getInstance();
- long locationCollectionTimeMillis = cal.getTimeInMillis();
- long refTimeMillis = locationCollectionTimeMillis
- - (TEST_LEGAL_DAYS - 1) * MILLISECONDS_PER_DAY;
-
- for (int i = 0; i < TEST_TOTAL_TIMES; ++i) {
- mDao.insertLocationHistoryData(
- locationCollectionTimeMillis, TEST_LATITUDE, TEST_LONGITUDE, 1, true);
- locationCollectionTimeMillis -= MILLISECONDS_PER_DAY;
- }
- Cursor cursor = mDao.readLocationInLastXDays(TEST_LEGAL_DAYS);
- assertNotNull(cursor);
- assertEquals(TEST_LEGAL_DAYS, cursor.getCount());
- if (cursor.moveToFirst()) {
- while (!cursor.isAfterLast()) {
- assertEquals(refTimeMillis, cursor.getLong(cursor.getColumnIndex(
- UserDataTables.LocationHistory.TIME_SEC)));
- assertEquals(TEST_LATITUDE, cursor.getString(cursor.getColumnIndex(
- UserDataTables.LocationHistory.LATITUDE)));
- assertEquals(TEST_LONGITUDE, cursor.getString(cursor.getColumnIndex(
- UserDataTables.LocationHistory.LONGITUDE)));
- assertEquals(1, cursor.getInt(cursor.getColumnIndex(
- UserDataTables.LocationHistory.SOURCE)));
- assertTrue(cursor.getInt(cursor.getColumnIndex(
- UserDataTables.LocationHistory.IS_PRECISE)) > 0);
- cursor.moveToNext();
- refTimeMillis += MILLISECONDS_PER_DAY;
- }
- }
-
- cursor = mDao.readLocationInLastXDays(TEST_ILLEGAL_DAYS);
- assertNull(cursor);
- }
-
- @After
- public void cleanup() {
- OnDevicePersonalizationDbHelper dbHelper =
- OnDevicePersonalizationDbHelper.getInstanceForTest(mContext);
- dbHelper.getWritableDatabase().close();
- dbHelper.getReadableDatabase().close();
- dbHelper.close();
- }
-}