目 录CONTENT

文章目录

Android 电池相关信息获取工具类封装

Stars-one
2025-01-10 / 0 评论 / 0 点赞 / 6 阅读 / 8261 字

Android 电池相关信息获取的工具类封装 示例代码

package aatiny.kk.reco.utils

import aatiny.kk.reco.R
import aatiny.kk.reco.application
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.BatteryManager
import kotlin.math.roundToInt

object BatteryUtil {

    /**
     * 电池相关信息
     *
     * @property totalCapacityStr 总容量,示例: 5000mAh
     * @property currentCapacityStr 当前电池容量,可能会比总容量少,示例: 5000mAh
     * @property requiredCapacity 当前剩余电池容量百分比,示例:70%
     * @property baPercent 电量百分比,示例: 100%
     * @property temperature 电池温度,示例: 26℃
     * @property voltage 电池电压,示例:4.3V
     * @property health 电池健康度,示例:good
     * @property technology 电池技术,示例:Li-poly
     * @property batteryStatus 电池充电状态,示例:full
     * @property batteryPlugged 充电方式,示例:ac
     */
    data class BatteryInfo(
        val totalCapacityStr: String,
        val currentCapacityStr: String,
        val baPercent: String,
        val temperature: String,
        val voltage: String,
        val health: String,
        val technology: String,
        val batteryStatus: String,
        val batteryPlugged: String,
        val requiredCapacity: String
    ) {

        fun isCharging(): Boolean {
            if (batteryStatus == "charging") {
                return true
            }
            return false
        }
    }

    fun getInfo(context: Context): BatteryInfo? {
        val filter = IntentFilter(Intent.ACTION_BATTERY_CHANGED)
        val info = context.registerReceiver(null, filter)?.run {
            val batteryManager = context.getSystemService(Context.BATTERY_SERVICE) as BatteryManager
            val batteryCapacity =
                batteryManager.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY).toDouble()

            val temperature =
                getIntExtra(BatteryManager.EXTRA_TEMPERATURE, 0).div(10.0).toString() + "°C"

            val voltage = getIntExtra(BatteryManager.EXTRA_VOLTAGE, 0).run {
                //将mV转为V,保留2位小数
                val one = this.div(1000.0)
                val str = String.format("%.2f", one)
                str + "V"
            }

            val health = batteryHealth(getIntExtra(BatteryManager.EXTRA_HEALTH, 2))

            //电量百分比,100即是100%
            val level = getIntExtra(BatteryManager.EXTRA_LEVEL, 0)
            val baPercent = "$level%"


            //电池总量
            val totalCapacity = getBatteryTotal(context)
            //当前电池容量
            val requiredCapacity = batteryCapacity / 100.0

            val currentCapactiy = (totalCapacity * requiredCapacity).roundToInt()

            val totalCapacityStr = totalCapacity.toInt().toString() + "mAh"
            val currentCapacityStr = currentCapactiy.toString() + "mAh"

            //电池类型,示例Li-poly
            val technology = getStringExtra(BatteryManager.EXTRA_TECHNOLOGY)

            val status = getIntExtra(BatteryManager.EXTRA_STATUS, 0)
            val plugged = getIntExtra(BatteryManager.EXTRA_PLUGGED, 0)

            //充电状态
            val batteryStatus = batteryStatus(status)

            //充电方式
            val batteryPlugged = batteryPlugged(plugged)

            //Log.d("ttt", "电池总容量: ${totalCapacityStr}")
            //Log.d("ttt", "电池当前容量: ${currentCapacityStr}")
            //Log.d("ttt", "电量百分比: ${baPercent}")
            //Log.d("ttt", "temperature: ${temperature}")
            //Log.d("ttt", "voltage: ${voltage}")
            //Log.d("ttt", "health: ${health}")
            //Log.d("ttt", "level: ${level}")
            //Log.d("ttt", "technology: ${technology}")
            //Log.d("ttt", "充电状态: $batteryStatus")
            //Log.d("ttt", "充电方式: $batteryPlugged")

            BatteryInfo(
                totalCapacityStr,
                currentCapacityStr,
                baPercent,
                temperature,
                voltage,
                health,
                technology ?: "unknown",
                batteryStatus,
                batteryPlugged,
                "${batteryCapacity.roundToInt()}%"
            )
        }
        return info
    }


    /**
     * 获取电池的容量
     *
     * @param context
     * @return
     */
    private fun getBatteryTotal(context: Context): Double {
        val mPowerProfile: Any
        val POWER_PROFILE_CLASS = "com.android.internal.os.PowerProfile"
        try {
            mPowerProfile = Class.forName(POWER_PROFILE_CLASS).getConstructor(Context::class.java)
                .newInstance(context)
            val batteryCapacity = Class.forName(POWER_PROFILE_CLASS).getMethod("getBatteryCapacity")
                .invoke(mPowerProfile) as Double
            return batteryCapacity
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return 0.0
    }

    private fun batteryHealth(health: Int): String {
        val context = application
        var healthBat = context.getString(R.string.unknown)
        when (health) {
            BatteryManager.BATTERY_HEALTH_COLD -> healthBat = context.getString(R.string.code)
            BatteryManager.BATTERY_HEALTH_DEAD -> healthBat = context.getString(R.string.dead)
            BatteryManager.BATTERY_HEALTH_GOOD -> healthBat = context.getString(R.string.good)
            BatteryManager.BATTERY_HEALTH_OVER_VOLTAGE -> healthBat = context.getString(R.string.overVol)
            BatteryManager.BATTERY_HEALTH_OVERHEAT -> healthBat = context.getString(R.string.overheat)
            BatteryManager.BATTERY_HEALTH_UNKNOWN -> healthBat = context.getString(R.string.unknown)
            BatteryManager.BATTERY_HEALTH_UNSPECIFIED_FAILURE -> healthBat = context.getString(R.string.unspecified)
        }
        return healthBat
    }

    private fun batteryPlugged(status: Int): String {
        val context = application
        var healthBat: String = context.getString(R.string.unknown)
        when (status) {
            BatteryManager.BATTERY_PLUGGED_AC -> healthBat = "ac"
            BatteryManager.BATTERY_PLUGGED_USB -> healthBat = "usb"
            BatteryManager.BATTERY_PLUGGED_WIRELESS -> healthBat = "wireless"
        }
        return healthBat
    }

    private fun batteryStatus(status: Int): String {
        val context = application
        var healthBat = context.getString(R.string.unknown)
        when (status) {
            BatteryManager.BATTERY_STATUS_CHARGING -> healthBat = context.getString(R.string.charing)
            BatteryManager.BATTERY_STATUS_FULL -> healthBat = context.getString(R.string.full)
            BatteryManager.BATTERY_STATUS_DISCHARGING -> healthBat = context.getString(R.string.dischargin)
            BatteryManager.BATTERY_STATUS_NOT_CHARGING -> healthBat = context.getString(R.string.nocharging)
            BatteryManager.BATTERY_STATUS_UNKNOWN -> healthBat =  context.getString(R.string.unknown)
        }
        return healthBat
    }

}
0

评论区