监控电池充电状态的变化

时间:2013-10-28 19:35:41

标签: android state battery batterylevel

这是我的代码,成功显示充电,电压和电池电量的当前状态。但是当充电器拔出或插上时(即当状态发生变化时,那么我的应用程序FORCE CLOSES)。任何身体请帮助,因为我是Android的新手。感谢。

public class MainActivity extends Activity {
private TextView batteryPercent;

private void batteryLevelUpdate() {
    BroadcastReceiver batteryLevelReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            context.unregisterReceiver(this);
            int rawlevel = intent.getIntExtra(BatteryManager.EXTRA_LEVEL,
                    -1);
            int scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
            int level = -1;
            if (rawlevel >= 0 && scale > 0) {
                level = (rawlevel * 100) / scale;
            }
            int voltage = intent.getIntExtra(BatteryManager.EXTRA_VOLTAGE,
                    -1);
            int status = intent
                    .getIntExtra(BatteryManager.EXTRA_STATUS, -1);
            int onplug = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED,
                    -1);
            boolean isCharging = status == BatteryManager.BATTERY_STATUS_CHARGING
                    || status == BatteryManager.BATTERY_STATUS_FULL;
            boolean onUSB = onplug == BatteryManager.BATTERY_PLUGGED_USB;
            boolean onAC = onplug == BatteryManager.BATTERY_PLUGGED_AC;
            String strStatus = "Charging on ";
            if (isCharging && onUSB)
                strStatus += "USB";
            else if (isCharging && onAC)
                strStatus += "AC Power";
            else
                strStatus = "Battery Discharging";
            batteryPercent.setText("Status=" + strStatus + "\nVoltage="
                    + voltage + "\nLevel=" + level + "%");
        }
    };
    IntentFilter batteryLevelFilter = new IntentFilter(
            Intent.ACTION_BATTERY_CHANGED);
    registerReceiver(batteryLevelReceiver, batteryLevelFilter);
}

/* @Override */
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    batteryPercent = (TextView) this.findViewById(R.id.batteryLevel);
    batteryLevelUpdate();
}

0 个答案:

没有答案