获取方法如下
Java写法:
private int getPhoneBattery(Context context) {
int level = 0;
Intent batteryInfoIntent = context.getApplicationContext().registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
level = batteryInfoIntent.getIntExtra("level", 0);
int batterySum = batteryInfoIntent.getIntExtra("scale", 100);
return 100 * level / batterySum;
}
Kotlin写法
private fun getPhoneBattery(context: Context): Int {
var level = 0
var batterySum = 100
val batteryInfoIntent: Intent? = context.applicationContext.registerReceiver(null, IntentFilter(Intent.ACTION_BATTERY_CHANGED))
if (batteryInfoIntent != null) {
level = batteryInfoIntent.getIntExtra("level", 0)
batterySum = batteryInfoIntent.getIntExtra("scale", 100)
}
return 100 * level / batterySum
}
|