public class BatteryChangedReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
//当前电量
int currLevel = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, 0);
//总电量
int total = intent.getIntExtra(BatteryManager.EXTRA_SCALE, 1);
int percent = currLevel * 100 / total;
}
}
在清单文件配置以下XMl:
<receiver android:name=".BatteryChangedReceiver">
<intent-filter>
<action android:name="android.intent.action.BATTERY_CHANGED"/>
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</receiver>
立即获取电量的,而不是等电量变化的广播,比如当阅读软件打开时立即显示出电池电量。我们可以按以下方式获取:
Intent batteryIntent = getApplicationContext().registerReceiver(null,
new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
int currLevel = batteryIntent.getIntExtra(BatteryManager.EXTRA_LEVEL, 0);
int total = batteryIntent.getIntExtra(BatteryManager.EXTRA_SCALE, 1);
int percent = currLevel * 100 / total;