我的应用程序显示电池电量..我有三个电池图像;一个绿色,一个黄色,另一个红色。当电池电量变化时,我想在imageview中放置这些图像。例如:当电池为100%时,将有绿色电池,50%黄色和20%红色。我该怎么做?现在我在listview中有一个静态图像,就像这样:
<ImageView
android:id="@+id/BatteryInfoimage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:contentDescription="image"
android:adjustViewBounds="true"
android:src="@drawable/battery"
/>
由于
答案 0 :(得分:1)
您可以使用BatteryManager获取电池电量。请参阅文档here
int level = batteryStatus.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
int scale = batteryStatus.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
float batteryPct = level / (float)scale;
现在从代码取决于batterPct设置特定图像
要监控更改,请使用以下
声明BroadCastReceiver
<receiver android:name=".PowerConnectionReceiver">
<intent-filter>
<action android:name="android.intent.action.ACTION_POWER_CONNECTED"/>
<action android:name="android.intent.action.ACTION_POWER_DISCONNECTED"/>
</intent-filter>
</receiver>
在关联的BroadcastReceiver实现中,您可以按照上一步中的描述提取当前的计费状态和方法。
public class PowerConnectionReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
int status = intent.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
boolean isCharging = status == BatteryManager.BATTERY_STATUS_CHARGING ||
status == BatteryManager.BATTERY_STATUS_FULL;
int chargePlug = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1);
boolean usbCharge = chargePlug == BatteryManager.BATTERY_PLUGGED_USB;
boolean acCharge = chargePlug == BatteryManager.BATTERY_PLUGGED_AC;
}
}