Lets talk today about how to get battery stats in the real time! :)
Sample activity:
public class ChargeSourceInfoActivity extends Activity {
TextView chargeSourceInfo;
private TextView battLevel, battVolt, battTemp,
battTech, battStatus, battConn;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.chargesource);
chargeSourceInfo = (TextView) this.findViewById(R.id.txtChargeSourceInfo);
LinearLayout ll = (LinearLayout) findViewById(R.id.mainLayout);
ll.setBackgroundResource(R.drawable.bg);
battLevel = (TextView)findViewById(R.id.txtBattLevel);
battVolt = (TextView)findViewById(R.id.txtBattVolt);
battTemp = (TextView)findViewById(R.id.txtBattTemp);
battTech = (TextView)findViewById(R.id.txtBattTech);
battStatus = (TextView)findViewById(R.id.txtBattStatus);
battConn = (TextView)findViewById(R.id.txtBattConn);
}
@Override
public void onResume() {
super.onResume();
registerReceiver(mBatteryInfoReceiver, new IntentFilter(
Intent.ACTION_BATTERY_CHANGED));
}
@Override
public void onPause() {
super.onPause();
unregisterReceiver(mBatteryInfoReceiver);
}
private BroadcastReceiver mBatteryInfoReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (Intent.ACTION_BATTERY_CHANGED.equals(action)) {
battLevel.setText("Level: "
+ String.valueOf(intent.getIntExtra("level", 0)) + "%");
battVolt.setText("Voltage: "
+ String.valueOf((float)intent.getIntExtra("voltage", 0)/1000) + "V");
battTemp.setText("Temperature: "
+ String.valueOf((float)intent.getIntExtra("temperature", 0)/10) + "c");
battTech.setText("Technology: " + intent.getStringExtra("technology"));
int status = intent.getIntExtra("status", BatteryManager.BATTERY_STATUS_UNKNOWN);
String strStatus;
if (status == BatteryManager.BATTERY_STATUS_CHARGING){
strStatus = "Charging";
} else if (status == BatteryManager.BATTERY_STATUS_DISCHARGING){
strStatus = "Dis-charging";
} else if (status == BatteryManager.BATTERY_STATUS_NOT_CHARGING){
strStatus = "Not charging";
} else if (status == BatteryManager.BATTERY_STATUS_FULL){
strStatus = "Full";
} else {
strStatus = "Unknown";
}
battStatus.setText("AC charging status: " + strStatus);
int plugged = intent.getIntExtra("plugged", 0);
if (plugged == BatteryManager.BATTERY_PLUGGED_AC){
strStatus = "AC";
} else if (plugged == BatteryManager.BATTERY_PLUGGED_USB){
strStatus = "USB";
} else {
strStatus = "None";
}
battConn.setText("Charge Connection: " + strStatus);
Idea: recieve and handle Intent.ACTION_BATTERY_CHANGED.
By this way we are able to get a lot of information about the battery health.
You can discover BatteryManager.* constants to check what additional info you are able to retrieve.
Happy charging and disharging! (:
Related topic, how to get battery stats via shell
Best regards,
Yahor
thanks really this is useful
ReplyDeleteHello,
ReplyDeleteYou are always very welcome!
Best regards,
Yahor