How can I get battery level and state (plugged in, discharging, charging, etc)? I researched the developer docs and I found a BatteryManager class. But it开发者_StackOverflow社区 doesn't contain any methods, just constants. How do I even use it?
Tutorial For Android has a code sample that explains how to get battery information.
To sum it up, a broadcast receiver for the ACTION_BATTERY_CHANGED
intent is set up dynamically, because it can not be received through components declared in manifests, only by explicitly registering for it with Context.registerReceiver()
.
public class Main extends Activity {
private TextView batteryTxt;
private BroadcastReceiver mBatInfoReceiver = new BroadcastReceiver(){
@Override
public void onReceive(Context ctxt, Intent intent) {
int level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
int scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
float batteryPct = level * 100 / (float)scale;
batteryTxt.setText(String.valueOf(batteryPct) + "%");
}
};
@Override
public void onCreate(Bundle b) {
super.onCreate(b);
setContentView(R.layout.main);
batteryTxt = (TextView) this.findViewById(R.id.batteryTxt);
this.registerReceiver(this.mBatInfoReceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
}
}
Since SDK 21
LOLLIPOP
it is possible to use the following to get current battery level as a percentage:
BatteryManager bm = (BatteryManager) context.getSystemService(BATTERY_SERVICE);
int batLevel = bm.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY);
Read BatteryManager | Android Developers - BATTERY_PROPERTY_CAPACITY
Based on official android docs, you can use this method in a Helper or Util class to get current battery percentage:
Java version:
public static int getBatteryPercentage(Context context) {
if (Build.VERSION.SDK_INT >= 21) {
BatteryManager bm = (BatteryManager) context.getSystemService(BATTERY_SERVICE);
return bm.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY);
} else {
IntentFilter iFilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
Intent batteryStatus = context.registerReceiver(null, iFilter);
int level = batteryStatus != null ? batteryStatus.getIntExtra(BatteryManager.EXTRA_LEVEL, -1) : -1;
int scale = batteryStatus != null ? batteryStatus.getIntExtra(BatteryManager.EXTRA_SCALE, -1) : -1;
double batteryPct = level / (double) scale;
return (int) (batteryPct * 100);
}
}
Kotlin version:
fun getBatteryPercentage(context: Context): Int {
return if (Build.VERSION.SDK_INT >= 21) {
val bm = context.getSystemService(BATTERY_SERVICE) as BatteryManager
bm.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY)
} else {
val iFilter = IntentFilter(Intent.ACTION_BATTERY_CHANGED)
val batteryStatus: Intent = context.registerReceiver(null, iFilter)
val level = batteryStatus?.getIntExtra(BatteryManager.EXTRA_LEVEL, -1)
val scale = batteryStatus?.getIntExtra(BatteryManager.EXTRA_SCALE, -1)
val batteryPct = level / scale.toDouble()
(batteryPct * 100).toInt()
}
}
You don't have to register an actual BroadcastReceiver as Android's BatteryManager is using a sticky Intent:
IntentFilter ifilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
Intent batteryStatus = registerReceiver(null, ifilter);
int level = batteryStatus.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
int scale = batteryStatus.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
float batteryPct = level / (float)scale;
return (int)(batteryPct*100);
This is from the official docs over at https://developer.android.com/training/monitoring-device-state/battery-monitoring.html.
Other answers didn't mention how to access battery status (chraging or not).
IntentFilter ifilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
Intent batteryStatus = context.registerReceiver(null, ifilter);
// Are we charging / charged?
int status = batteryStatus.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
boolean isCharging = status == BatteryManager.BATTERY_STATUS_CHARGING ||
status == BatteryManager.BATTERY_STATUS_FULL;
// How are we charging?
int chargePlug = batteryStatus.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1);
boolean usbCharge = chargePlug == BatteryManager.BATTERY_PLUGGED_USB;
boolean acCharge = chargePlug == BatteryManager.BATTERY_PLUGGED_AC;
You can use this to get remaining charged in percentage.
private void batteryLevel() {
BroadcastReceiver batteryLevelReceiver = new BroadcastReceiver() {
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;
}
batterLevel.setText("Battery Level Remaining: " + level + "%");
}
};
IntentFilter batteryLevelFilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
registerReceiver(batteryLevelReceiver, batteryLevelFilter);
}
try this function no need permisson or any reciver
void getBattery_percentage()
{
IntentFilter ifilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
Intent batteryStatus = getApplicationContext().registerReceiver(null, ifilter);
int level = batteryStatus.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
int scale = batteryStatus.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
float batteryPct = level / (float)scale;
float p = batteryPct * 100;
Log.d("Battery percentage",String.valueOf(Math.round(p)));
}
To check battery percentage we use BatteryManager, the following method will return battery percentage.
Source Link
public static float getBatteryLevel(Context context, Intent intent) {
Intent batteryStatus = context.registerReceiver(null,
new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
int batteryLevel = -1;
int batteryScale = 1;
if (batteryStatus != null) {
batteryLevel = batteryStatus.getIntExtra(BatteryManager.EXTRA_LEVEL, batteryLevel);
batteryScale = batteryStatus.getIntExtra(BatteryManager.EXTRA_SCALE, batteryScale);
}
return batteryLevel / (float) batteryScale * 100;
}
one mistake in official docs, you must use double instead float. Because 0.53F * 100F = 52F
int level = batteryStatus != null ?
batteryStatus.getIntExtra(BatteryManager.EXTRA_LEVEL, -1) : -1; int scale =
batteryStatus != null ? batteryStatus.getIntExtra(BatteryManager.EXTRA_SCALE, -1) : -1;
double batteryPct = (double) level / (double) scale; int percent = (int) (batteryPct * 100D);
private void batteryLevel() {
BroadcastReceiver batteryLevelReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
context.unregisterReceiver(this);
int rawlevel = intent.getIntExtra("level", -1);
int scale = intent.getIntExtra("scale", -1);
int level = -1;
if (rawlevel >= 0 && scale > 0) {
level = (rawlevel * 100) / scale;
}
mBtn.setText("Battery Level Remaining: " + level + "%");
}
};
IntentFilter batteryLevelFilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
registerReceiver(batteryLevelReceiver, batteryLevelFilter);
}
get battery level in Android-Kotlin:
class MainActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
registerReceiver(this.broadcastReceiver, IntentFilter(Intent.ACTION_BATTERY_CHANGED))
}
private val broadcastReceiver: BroadcastReceiver = object : BroadcastReceiver() {
@SuppressLint("SetTextI18n")
override fun onReceive(context: Context?, intent: Intent) {
val level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, 0)
binding.txtShowBatteryLevel.text = "Battery level: %$level"
}
}
}
Based on these great answers I modified the getBatteryPercentage. Btw I used "Carlson Notation" code formatting because it's just plain easier to read fast.
public static String getBatteryPercentage(Context context)
{
String bstatus = "isChrg=false usbChrg=false acChrg=false wlChrg=false 0% t=70°F";
IntentFilter iFilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
Intent batteryStatus = context.registerReceiver(null, iFilter);
int status = batteryStatus.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
boolean isCharging = status == BatteryManager.BATTERY_STATUS_CHARGING ||
status == BatteryManager.BATTERY_STATUS_FULL;
int level = batteryStatus.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
int scale = batteryStatus.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
float batteryPct = level * 100 / (float)scale;
//How are we charging?
int chargePlug = batteryStatus.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1);
boolean usbCharge = chargePlug == BatteryManager.BATTERY_PLUGGED_USB;
boolean acCharge = chargePlug == BatteryManager.BATTERY_PLUGGED_AC;
boolean wlCharge = chargePlug == BatteryManager.BATTERY_PLUGGED_WIRELESS;
int temp = batteryStatus.getIntExtra(BatteryManager.EXTRA_TEMPERATURE,0);
float tempTwo = ((float) temp) / 10;
double d = CelsiusToFahrenheit(tempTwo);
bstatus = String.format(Locale.US, "isChrg=%b usbChrg=%b acChrg=%b wlChrg=%b %.0f%% t=%.2f°F",
isCharging,
usbCharge,
acCharge,
wlCharge,
batteryPct,
d);
return bstatus;
}
精彩评论