这是我的代码,它成功显示了当前充电状态、电压和电池电量。但是当充电器拔出或插入时(即当状态发生变化时,我的应用程序将强制关闭)。任何机构请帮助,因为我是 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();
}