当前位置:   article > 正文

Android获取手机电压,电流,电量,BatteryManager_android batterymanager

android batterymanager
//手机电流
BatteryManager mBatteryManager = (BatteryManager)getSystemService(Context.BATTERY_SERVICE);
int energy = mBatteryManager.getIntProperty(BatteryManager.BATTERY_PROPERTY_CURRENT_NOW);
BroadcastReceiver batteryChangedReceiver = new BroadcastReceiver() {
    public void onReceive(Context context, Intent intent) {

        int rawlevel = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
              //电池电量最大值
        int scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
        //电压
        int intExtra = intent.getIntExtra(BatteryManager.EXTRA_VOLTAGE, -1)/1000;


        if ((rawlevel >= 0) && (scale > 0)) {
//当前电量
            mBatteryLevel = (rawlevel * 100) / scale;
            Log.e("电量情况", mBatteryLevel + "");
        } else {
            mBatteryLevel = -1;

        }
        int status = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1);
        if (status != -1) {
            switch (status) {
                case 0:
                    mPowerSource = "电池供电";
                    if (mBatteryLevel < powerlow) {// 低于电量下限值向平台发充电质量
                        Log.e(TAG, "onReceive: =======低电量==========" );

                    } else {
                        Log.e(TAG, "onReceive: =======未充电==========" );

                    }
                    break;
                case BatteryManager.BATTERY_PLUGGED_AC:
                    mPowerSource = "交流供电";
                    Log.e(TAG, "onReceive: =======正在充电==========" );

                    if (mBatteryLevel > powerhigh) {// 充电的时候发现当前的电量高于上限向平台发送断电指令
                        Log.e(TAG, "onReceive: =======已充满,请断电!==========" );
                    }
                    break;

                case BatteryManager.BATTERY_PLUGGED_USB:
                    mPowerSource = "USB供电";
                    Log.e(TAG, "onReceive: =======正在充电==========" );
                    if (mBatteryLevel > powerhigh) {
                        Log.e(TAG, "onReceive: =======已充满,请断电!==========" );
                    }
                    break;
            }
        }
    }
};

Activity注册

// 定义电池电量更新广播的过滤器,只接受带有ACTION_BATTERRY_CHANGED事件的Intent
IntentFilter batteryChangedReceiverFilter = new IntentFilter();
batteryChangedReceiverFilter.addAction(Intent.ACTION_BATTERY_CHANGED);//
// 向系统注册batteryChangedReceiver接收器,本接收器的实现见代码字段处
registerReceiver(batteryChangedReceiver, batteryChangedReceiverFilter);

反注册

unregisterReceiver(batteryChangedReceiver);
本文内容由网友自发贡献,转载请注明出处:【wpsshop博客】
推荐阅读
相关标签
  

闽ICP备14008679号