my application show the battery level.. I have three batteries images; One gree, one yellow and another one red. I want place in a imageview these images when battery level change.. For example: when the battery is 100% there will be the green battery, when 50% the yellow and 20% red. How can i do it? For now i have a static image in a listview simply like this:
<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"
/>
Thanks
you can get the battery level using BatteryManager. see the doc here
int level = batteryStatus.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
int scale = batteryStatus.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
float batteryPct = level / (float)scale;
Now from the code depending of the batterPct set the specific image
And to Monitor the change use the following
Declare a 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>
Within the associated BroadcastReceiver implementation, you can extract the current charging state and method as described in the previous step.
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;
}
}