1 /* 2 * Copyright (C) 2020 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.power.stats; 18 19 import android.os.BatteryConsumer; 20 import android.os.BatteryStats; 21 import android.os.BatteryUsageStats; 22 import android.os.BatteryUsageStatsQuery; 23 import android.os.Process; 24 import android.os.UidBatteryConsumer; 25 import android.os.UserHandle; 26 import android.util.SparseArray; 27 28 import com.android.internal.util.ArrayUtils; 29 30 /** 31 * Computes power consumed by Users 32 */ 33 public class UserPowerCalculator extends PowerCalculator { 34 35 @Override isPowerComponentSupported(@atteryConsumer.PowerComponent int powerComponent)36 public boolean isPowerComponentSupported(@BatteryConsumer.PowerComponent int powerComponent) { 37 return true; 38 } 39 40 @Override calculate(BatteryUsageStats.Builder builder, BatteryStats batteryStats, long rawRealtimeUs, long rawUptimeUs, BatteryUsageStatsQuery query)41 public void calculate(BatteryUsageStats.Builder builder, BatteryStats batteryStats, 42 long rawRealtimeUs, long rawUptimeUs, BatteryUsageStatsQuery query) { 43 final int[] userIds = query.getUserIds(); 44 if (ArrayUtils.contains(userIds, UserHandle.USER_ALL)) { 45 return; 46 } 47 48 SparseArray<UidBatteryConsumer.Builder> uidBatteryConsumerBuilders = 49 builder.getUidBatteryConsumerBuilders(); 50 51 for (int i = uidBatteryConsumerBuilders.size() - 1; i >= 0; i--) { 52 final UidBatteryConsumer.Builder uidBuilder = uidBatteryConsumerBuilders.valueAt(i); 53 if (uidBuilder.isVirtualUid()) { 54 continue; 55 } 56 57 final int uid = uidBuilder.getUid(); 58 if (UserHandle.getAppId(uid) < Process.FIRST_APPLICATION_UID) { 59 continue; 60 } 61 62 final int userId = UserHandle.getUserId(uid); 63 if (!ArrayUtils.contains(userIds, userId)) { 64 uidBuilder.excludeFromBatteryUsageStats(); 65 builder.getOrCreateUserBatteryConsumerBuilder(userId) 66 .addUidBatteryConsumer(uidBuilder); 67 } 68 } 69 } 70 } 71