package com.base.locationsharewhite.fcm

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

/**
 *电量监听
 */
class BatteryStatusReceiver : BroadcastReceiver() {

    companion object {
        fun registerBatteryReceiver(context: Context) {
            val intentFilter = IntentFilter().apply {
                addAction(Intent.ACTION_BATTERY_CHANGED)
            }
            val applicationContext = context.applicationContext
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
                applicationContext.registerReceiver(
                    BatteryStatusReceiver(),
                    intentFilter,
                    Context.RECEIVER_EXPORTED
                )
            } else {
                applicationContext.registerReceiver(BatteryStatusReceiver(), intentFilter)
            }
        }
    }

    override fun onReceive(context: Context?, intent: Intent?) {
        val action = intent?.action
        if (action == Intent.ACTION_BATTERY_CHANGED) {
            val batteryLevel = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1)
            val batteryScale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1)
            val batteryPercentage = (batteryLevel / batteryScale.toFloat()) * 100

        }

    }
}