Merge "Add BatteryHistoricalLogUtil class"
This commit is contained in:
@@ -41,6 +41,7 @@ import com.android.settings.applications.appinfo.ButtonActionDialogFragment;
|
||||
import com.android.settings.core.InstrumentedPreferenceFragment;
|
||||
import com.android.settings.core.SubSettingLauncher;
|
||||
import com.android.settings.dashboard.DashboardFragment;
|
||||
import com.android.settings.fuelgauge.BatteryOptimizeHistoricalLogEntry.Action;
|
||||
import com.android.settings.fuelgauge.batteryusage.BatteryDiffEntry;
|
||||
import com.android.settings.fuelgauge.batteryusage.BatteryEntry;
|
||||
import com.android.settings.fuelgauge.batteryusage.BatteryHistEntry;
|
||||
@@ -113,6 +114,8 @@ public class AdvancedPowerUsageDetail extends DashboardFragment implements
|
||||
int mOptimizationMode = BatteryOptimizeUtils.MODE_UNKNOWN;
|
||||
@VisibleForTesting
|
||||
BackupManager mBackupManager;
|
||||
@VisibleForTesting
|
||||
StringBuilder mLogStringBuilder;
|
||||
|
||||
private AppButtonsPreferenceController mAppButtonsPreferenceController;
|
||||
|
||||
@@ -274,6 +277,7 @@ public class AdvancedPowerUsageDetail extends DashboardFragment implements
|
||||
getContext(),
|
||||
SettingsEnums.OPEN_APP_BATTERY_USAGE,
|
||||
packageName);
|
||||
mLogStringBuilder = new StringBuilder("onResume mode = ").append(mOptimizationMode);
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -283,8 +287,16 @@ public class AdvancedPowerUsageDetail extends DashboardFragment implements
|
||||
final int selectedPreference = getSelectedPreference();
|
||||
|
||||
notifyBackupManager();
|
||||
mLogStringBuilder.append(", onPause mode = ").append(selectedPreference);
|
||||
logMetricCategory(selectedPreference);
|
||||
mBatteryOptimizeUtils.setAppUsageState(selectedPreference);
|
||||
|
||||
BatteryHistoricalLogUtil.writeLog(
|
||||
getContext().getApplicationContext(),
|
||||
Action.MANUAL,
|
||||
BatteryHistoricalLogUtil.getPackageNameWithUserId(
|
||||
mBatteryOptimizeUtils.getPackageName(), UserHandle.myUserId()),
|
||||
mLogStringBuilder.toString());
|
||||
mBatteryOptimizeUtils.setAppUsageState(selectedPreference, Action.APPLY);
|
||||
Log.d(TAG, "Leave with mode: " + selectedPreference);
|
||||
}
|
||||
|
||||
|
@@ -221,7 +221,8 @@ public final class BatteryBackupHelper implements BackupHelper {
|
||||
mBatteryOptimizeUtils != null
|
||||
? mBatteryOptimizeUtils /*testing only*/
|
||||
: new BatteryOptimizeUtils(mContext, uid, packageName);
|
||||
batteryOptimizeUtils.setAppUsageState(mode);
|
||||
batteryOptimizeUtils.setAppUsageState(
|
||||
mode, BatteryOptimizeHistoricalLogEntry.Action.RESTORE);
|
||||
Log.d(TAG, String.format("restore:%s mode=%d", packageName, mode));
|
||||
}
|
||||
|
||||
|
129
src/com/android/settings/fuelgauge/BatteryHistoricalLogUtil.java
Normal file
129
src/com/android/settings/fuelgauge/BatteryHistoricalLogUtil.java
Normal file
@@ -0,0 +1,129 @@
|
||||
/*
|
||||
* 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.settings.fuelgauge;
|
||||
|
||||
import android.content.Context;
|
||||
import android.content.SharedPreferences;
|
||||
import android.util.Base64;
|
||||
import android.util.Log;
|
||||
|
||||
import com.android.settings.fuelgauge.BatteryOptimizeHistoricalLogEntry.Action;
|
||||
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import com.google.protobuf.InvalidProtocolBufferException;
|
||||
import com.google.protobuf.MessageLite;
|
||||
|
||||
import java.io.PrintWriter;
|
||||
import java.util.List;
|
||||
|
||||
/** Writes and reads a historical log of battery related state change events. */
|
||||
public final class BatteryHistoricalLogUtil {
|
||||
private static final String BATTERY_OPTIMIZE_FILE_NAME = "battery_optimize_historical_logs";
|
||||
private static final String LOGS_KEY = "battery_optimize_logs_key";
|
||||
private static final String TAG = "BatteryHistoricalLogUtil";
|
||||
|
||||
@VisibleForTesting
|
||||
static final int MAX_ENTRIES = 40;
|
||||
|
||||
/**
|
||||
* Writes a log entry.
|
||||
*
|
||||
* <p>Keeps up to {@link #MAX_ENTRIES} in the log, once that number is exceeded, it prunes the
|
||||
* oldest one.
|
||||
*/
|
||||
static void writeLog(Context context, Action action, String pkg, String actionDescription) {
|
||||
writeLog(
|
||||
context,
|
||||
BatteryOptimizeHistoricalLogEntry.newBuilder()
|
||||
.setPackageName(pkg)
|
||||
.setAction(action)
|
||||
.setActionDescription(actionDescription)
|
||||
.build());
|
||||
}
|
||||
|
||||
private static void writeLog(Context context, BatteryOptimizeHistoricalLogEntry logEntry) {
|
||||
SharedPreferences sharedPreferences = getSharedPreferences(context);
|
||||
|
||||
BatteryOptimizeHistoricalLog existingLog =
|
||||
parseLogFromString(sharedPreferences.getString(LOGS_KEY, ""));
|
||||
BatteryOptimizeHistoricalLog.Builder newLogBuilder = existingLog.toBuilder();
|
||||
// Prune old entries
|
||||
if (existingLog.getLogEntryCount() >= MAX_ENTRIES) {
|
||||
newLogBuilder.removeLogEntry(0);
|
||||
}
|
||||
newLogBuilder.addLogEntry(logEntry);
|
||||
|
||||
sharedPreferences
|
||||
.edit()
|
||||
.putString(
|
||||
LOGS_KEY,
|
||||
Base64.encodeToString(newLogBuilder.build().toByteArray(), Base64.DEFAULT))
|
||||
.apply();
|
||||
}
|
||||
|
||||
private static BatteryOptimizeHistoricalLog parseLogFromString(String storedLogs) {
|
||||
return parseProtoFromString(storedLogs, BatteryOptimizeHistoricalLog.getDefaultInstance());
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
private static <T extends MessageLite> T parseProtoFromString(
|
||||
String serializedProto, T protoClass) {
|
||||
if (serializedProto.isEmpty()) {
|
||||
return (T) protoClass.getDefaultInstanceForType();
|
||||
}
|
||||
try {
|
||||
return (T) protoClass.getParserForType()
|
||||
.parseFrom(Base64.decode(serializedProto, Base64.DEFAULT));
|
||||
} catch (InvalidProtocolBufferException e) {
|
||||
Log.e(TAG, "Failed to deserialize proto class", e);
|
||||
return (T) protoClass.getDefaultInstanceForType();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Prints the historical log that has previously been stored by this utility.
|
||||
*/
|
||||
public static void printBatteryOptimizeHistoricalLog(Context context, PrintWriter writer) {
|
||||
writer.println("Battery optimize state history:");
|
||||
SharedPreferences sharedPreferences = getSharedPreferences(context);
|
||||
BatteryOptimizeHistoricalLog existingLog =
|
||||
parseLogFromString(sharedPreferences.getString(LOGS_KEY, ""));
|
||||
List<BatteryOptimizeHistoricalLogEntry> logEntryList = existingLog.getLogEntryList();
|
||||
if (logEntryList.isEmpty()) {
|
||||
writer.println("\tNo past logs.");
|
||||
} else {
|
||||
logEntryList.forEach(entry -> writer.println(toString(entry)));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the unique key for logging, combined with package name, delimiter and user id.
|
||||
*/
|
||||
static String getPackageNameWithUserId(String pkgName, int userId) {
|
||||
return pkgName + ":" + userId;
|
||||
}
|
||||
|
||||
private static String toString(BatteryOptimizeHistoricalLogEntry entry) {
|
||||
return String.format("%s\tAction:%s\tEvent:%s",
|
||||
entry.getPackageName(), entry.getAction(), entry.getActionDescription());
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
static SharedPreferences getSharedPreferences(Context context) {
|
||||
return context.getSharedPreferences(BATTERY_OPTIMIZE_FILE_NAME, Context.MODE_PRIVATE);
|
||||
}
|
||||
}
|
@@ -32,6 +32,7 @@ import android.util.Log;
|
||||
|
||||
import androidx.annotation.VisibleForTesting;
|
||||
|
||||
import com.android.settings.fuelgauge.BatteryOptimizeHistoricalLogEntry.Action;
|
||||
import com.android.settingslib.fuelgauge.PowerAllowlistBackend;
|
||||
|
||||
import java.lang.annotation.Retention;
|
||||
@@ -49,6 +50,7 @@ public class BatteryOptimizeUtils {
|
||||
@VisibleForTesting boolean mAllowListed;
|
||||
|
||||
private final String mPackageName;
|
||||
private final Context mContext;
|
||||
private final int mUid;
|
||||
|
||||
// If current user is admin, match apps from all users. Otherwise, only match the currect user.
|
||||
@@ -77,6 +79,7 @@ public class BatteryOptimizeUtils {
|
||||
|
||||
public BatteryOptimizeUtils(Context context, int uid, String packageName) {
|
||||
mUid = uid;
|
||||
mContext = context;
|
||||
mPackageName = packageName;
|
||||
mAppOpsManager = context.getSystemService(AppOpsManager.class);
|
||||
mBatteryUtils = BatteryUtils.getInstance(context);
|
||||
@@ -115,12 +118,13 @@ public class BatteryOptimizeUtils {
|
||||
}
|
||||
|
||||
/** Sets the {@link OptimizationMode} for associated app. */
|
||||
public void setAppUsageState(@OptimizationMode int mode) {
|
||||
public void setAppUsageState(@OptimizationMode int mode, Action action) {
|
||||
if (getAppOptimizationMode(mMode, mAllowListed) == mode) {
|
||||
Log.w(TAG, "set the same optimization mode for: " + mPackageName);
|
||||
return;
|
||||
}
|
||||
setAppUsageStateInternal(mode, mUid, mPackageName, mBatteryUtils, mPowerAllowListBackend);
|
||||
setAppUsageStateInternal(
|
||||
mContext, mode, mUid, mPackageName, mBatteryUtils, mPowerAllowListBackend, action);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -192,8 +196,8 @@ public class BatteryOptimizeUtils {
|
||||
}
|
||||
|
||||
// Resets to the default mode: MODE_OPTIMIZED.
|
||||
setAppUsageStateInternal(MODE_OPTIMIZED, info.uid, info.packageName, batteryUtils,
|
||||
allowlistBackend);
|
||||
setAppUsageStateInternal(context, MODE_OPTIMIZED, info.uid, info.packageName,
|
||||
batteryUtils, allowlistBackend, Action.RESET);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -208,8 +212,9 @@ public class BatteryOptimizeUtils {
|
||||
}
|
||||
|
||||
private static void setAppUsageStateInternal(
|
||||
@OptimizationMode int mode, int uid, String packageName, BatteryUtils batteryUtils,
|
||||
PowerAllowlistBackend powerAllowlistBackend) {
|
||||
Context context, @OptimizationMode int mode, int uid, String packageName,
|
||||
BatteryUtils batteryUtils, PowerAllowlistBackend powerAllowlistBackend,
|
||||
Action action) {
|
||||
if (mode == MODE_UNKNOWN) {
|
||||
Log.d(TAG, "set unknown app optimization mode.");
|
||||
return;
|
||||
@@ -223,14 +228,17 @@ public class BatteryOptimizeUtils {
|
||||
final boolean allowListed = mode == MODE_UNRESTRICTED;
|
||||
|
||||
AsyncTask.execute(() -> {
|
||||
setAppOptimizationModeInternal(appOpsManagerMode, allowListed, uid, packageName,
|
||||
batteryUtils, powerAllowlistBackend);
|
||||
setAppOptimizationModeInternal(context, appOpsManagerMode, allowListed, uid,
|
||||
packageName, batteryUtils, powerAllowlistBackend, action);
|
||||
});
|
||||
}
|
||||
|
||||
private static void setAppOptimizationModeInternal(
|
||||
int appStandbyMode, boolean allowListed, int uid, String packageName,
|
||||
BatteryUtils batteryUtils, PowerAllowlistBackend powerAllowlistBackend) {
|
||||
Context context, int appStandbyMode, boolean allowListed, int uid, String packageName,
|
||||
BatteryUtils batteryUtils, PowerAllowlistBackend powerAllowlistBackend,
|
||||
Action action) {
|
||||
final String packageNameKey = BatteryHistoricalLogUtil
|
||||
.getPackageNameWithUserId(packageName, UserHandle.myUserId());
|
||||
try {
|
||||
batteryUtils.setForceAppStandby(uid, packageName, appStandbyMode);
|
||||
if (allowListed) {
|
||||
@@ -239,8 +247,15 @@ public class BatteryOptimizeUtils {
|
||||
powerAllowlistBackend.removeApp(packageName);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
// Error cases, set standby mode as -1 for logging.
|
||||
appStandbyMode = -1;
|
||||
Log.e(TAG, "set OPTIMIZATION MODE failed for " + packageName, e);
|
||||
}
|
||||
BatteryHistoricalLogUtil.writeLog(
|
||||
context,
|
||||
action,
|
||||
packageNameKey,
|
||||
createLogEvent(appStandbyMode, allowListed));
|
||||
}
|
||||
|
||||
private void refreshState() {
|
||||
@@ -251,4 +266,12 @@ public class BatteryOptimizeUtils {
|
||||
Log.d(TAG, String.format("refresh %s state, allowlisted = %s, mode = %d",
|
||||
mPackageName, mAllowListed, mMode));
|
||||
}
|
||||
|
||||
private static String createLogEvent(int appStandbyMode, boolean allowListed) {
|
||||
return appStandbyMode < 0 ? "Apply optimize setting ERROR" :
|
||||
String.format("\tStandbyMode: %s, allowListed: %s, mode: %s",
|
||||
appStandbyMode,
|
||||
allowListed,
|
||||
getAppOptimizationMode(appStandbyMode, allowListed));
|
||||
}
|
||||
}
|
||||
|
Reference in New Issue
Block a user