1 /* 2 * Copyright 2024 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 * https://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 package com.android.devicediagnostics.evaluated 17 18 import android.content.Context 19 import android.content.Context.BATTERY_SERVICE 20 import android.content.Intent 21 import android.content.IntentFilter 22 import android.os.BatteryManager 23 import com.android.devicediagnostics.Protos.BatteryInfo 24 import com.android.devicediagnostics.R 25 getBatteryInfonull26fun getBatteryInfo(context: Context): BatteryInfo { 27 val builder = BatteryInfo.newBuilder() 28 val bm = context.getSystemService(BATTERY_SERVICE) as? BatteryManager 29 if (bm == null) return builder.build() 30 31 try { 32 var date = bm.getLongProperty(BatteryManager.BATTERY_PROPERTY_MANUFACTURING_DATE) 33 if (date >= 0) { 34 builder.setManufactureTimestamp(date) 35 } 36 37 date = bm.getLongProperty(BatteryManager.BATTERY_PROPERTY_FIRST_USAGE_DATE) 38 if (date >= 0) { 39 builder.setFirstUsageTimestamp(date) 40 } 41 } catch (e: Exception) {} 42 43 val stateOfHealth = bm.getIntProperty(BatteryManager.BATTERY_PROPERTY_STATE_OF_HEALTH) 44 if (stateOfHealth >= 0) { 45 builder.setStateOfHealth(stateOfHealth) 46 } 47 48 if (android.os.Flags.batteryPartStatusApi()) { 49 val status = bm.getIntProperty(BatteryManager.BATTERY_PROPERTY_PART_STATUS) 50 if (status == BatteryManager.PART_STATUS_ORIGINAL) { 51 builder.setPartStatus(context.resources.getString(R.string.battery_original)) 52 } else if (status == BatteryManager.PART_STATUS_REPLACED) { 53 builder.setPartStatus(context.resources.getString(R.string.battery_replaced)) 54 } 55 val serial = bm.getStringProperty(BatteryManager.BATTERY_PROPERTY_SERIAL_NUMBER) 56 if (!serial.isNullOrEmpty()) { 57 builder.setSerial(serial) 58 } 59 } 60 61 val filter = IntentFilter(Intent.ACTION_BATTERY_CHANGED) 62 val batteryStatus = context.registerReceiver(null, filter) 63 if (batteryStatus != null) { 64 builder.setCycleCount(batteryStatus.getIntExtra("android.os.extra.CYCLE_COUNT", -1)) 65 builder.setLegacyHealth(batteryStatus.getIntExtra(BatteryManager.EXTRA_HEALTH, -1)) 66 } 67 68 return builder.build() 69 } 70