码迷,mamicode.com
首页 > 其他好文 > 详细

电源信息监控

时间:2019-07-23 15:31:19      阅读:118      评论:0      收藏:0      [点我收藏+]

标签:extra   span   ext   cas   manage   eal   status   电源   监控   

定义接受电源信息的BroadCastReceiver

private val batteryBroadcastReceiver = object :BroadcastReceiver(){
        override fun onReceive(p0: Context?, p1: Intent?) {
            when(p1?.getIntExtra(BatteryManager.EXTRA_STATUS,BatteryManager.BATTERY_HEALTH_UNKNOWN)){
                BatteryManager.BATTERY_STATUS_CHARGING -> {
                    //充电中
                }

                BatteryManager.BATTERY_STATUS_FULL -> {
                    //已充满
                }

                else -> {
                    val level = p1?.getIntExtra(BatteryManager.EXTRA_LEVEL,0)//当前电量
                    val scale = p1?.getIntExtra(BatteryManager.EXTRA_SCALE,0)//总电量
                    val percentage = (level?.toFloat()!! * 100 / scale?.toFloat()!!).toInt()
                    
                }
            }
        }
    }

注册和销毁

context.registerReceiver(batteryBroadcastReceiver, IntentFilter(Intent.ACTION_BATTERY_CHANGED))


context.unregisterReceiver(batteryBroadcastReceiver)

 

电源信息监控

标签:extra   span   ext   cas   manage   eal   status   电源   监控   

原文地址:https://www.cnblogs.com/rchao/p/11231486.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!