これは、充電、電圧、およびバッテリーレベルの現在の状態を正常に表示する私のコードです。しかし、充電器が抜かれたり差し込まれたりすると(つまり、状態が変化すると、アプリケーションが強制的に閉じます)。私はアンドロイドが初めてなので、どんな体でも助けてください。ありがとう。
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();
}