package com.base.locationsharewhite.utils

import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.BatteryManager

object BatteryUtils {

    fun Context.getBatteryLevel(): Int {
        val batteryLevel: Int
        val intent = registerReceiver(null, IntentFilter(Intent.ACTION_BATTERY_CHANGED))
        return when {
            intent != null -> {
                val level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1)
                val scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1)
                batteryLevel = if (scale != -1) {
                    (level * 100 / scale).toInt()
                } else {
                    -1
                }
                batteryLevel
            }

            else -> -1 // 无法获取电量信息
        }
    }
}