AndroidStudio监测电池电量变化广播代码
时间: 2023-07-03 07:23:58 浏览: 128
以下是在Android Studio中监听电池电量变化广播的代码:
```java
public class BatteryBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
int batteryLevel = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
int batteryScale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
float batteryPercentage = batteryLevel * 100 / (float)batteryScale;
// Do something with batteryPercentage
}
}
```
在你的AndroidManifest.xml文件中添加以下代码来注册广播接收器:
```xml
<receiver android:name=".BatteryBroadcastReceiver">
<intent-filter>
<action android:name="android.intent.action.BATTERY_CHANGED" />
</intent-filter>
</receiver>
```
当电池电量变化时,`onReceive`方法将被调用,并且可以通过`intent`对象获取电池电量信息。
阅读全文