@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1) public static BatteryStatus getBatteryStatus(Context context) { Intent intent = context.registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED)); if (intent == null) { // should not happen return BatteryStatus.DEFAULT; } int level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1); int scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1); float batteryPct = level / (float) scale; // 0 is on battery int plugged = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, 0); boolean charging = plugged == BatteryManager.BATTERY_PLUGGED_AC || plugged == BatteryManager.BATTERY_PLUGGED_USB || (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1 && plugged == BatteryManager.BATTERY_PLUGGED_WIRELESS); return new BatteryStatus(charging, batteryPct); }
@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1) public static BatteryStatus getBatteryStatus(Context context) { Intent intent = context.registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED)); if (intent == null) { // should not happen return BatteryStatus.DEFAULT; } int level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1); int scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1); float batteryPct = level / (float) scale; // 0 is on battery int plugged = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, 0); boolean charging = plugged == BatteryManager.BATTERY_PLUGGED_AC || plugged == BatteryManager.BATTERY_PLUGGED_USB || (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1 && plugged == BatteryManager.BATTERY_PLUGGED_WIRELESS); return new BatteryStatus(charging, batteryPct); }