Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Android Wear: small gist to get data from Battery
public class BatteryActivity extends Activity {
//UI Elements
private TextView mTextViewLevel;
private TextView mTextViewTemperature;
private TextView mTextViewVoltage;
private TextView mTextViewHealth;
//Battery details
private int level;
private int voltage;
private int temperature;
private int healthState;
private int chargePlug;
private int status;
boolean celsius = true;
protected void onCreate(Bundle savedInstanceState) {
final WatchViewStub stub = (WatchViewStub) findViewById(;
stub.setOnLayoutInflatedListener(new WatchViewStub.OnLayoutInflatedListener() {
public void onLayoutInflated(WatchViewStub stub) {
//ui elements
mTextViewLevel = (TextView) stub.findViewById(;
mTextViewTemperature = (TextView) stub.findViewById(;
mTextViewVoltage = (TextView) stub.findViewById(;
mTextViewHealth = (TextView) stub.findViewById(;
//update battery details
private void updateBattery() {
IntentFilter ifilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
Intent batteryStatus = registerReceiver(null, ifilter);
level = batteryStatus.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
healthState = batteryStatus.getIntExtra(BatteryManager.EXTRA_HEALTH, -1);
int healthId = getResources().getIdentifier("battery_health_" + healthState,
"string", this.getPackageName());
String health = getString(healthId);
//Battery status
//status = batteryStatus.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
//int resIdCharging = getResources().getIdentifier("charging_" + status,"string", this.getPackageName());
//String charging = getString(resIdCharging);
temperature = batteryStatus.getIntExtra(
BatteryManager.EXTRA_TEMPERATURE, 0);
if (celsius){
temperature= temperature/10;
temperature= temperature/10;
//temperature= (int)( (float)((9.0f * temperature) / 5.0f) + 32.0f);
temperature= (int)( 9.0 * temperature / 5.0 + 32.0);
voltage = batteryStatus.getIntExtra(BatteryManager.EXTRA_VOLTAGE, 0);
//chargePlug = batteryStatus.getIntExtra(
// BatteryManager.EXTRA_PLUGGED, -1);
//int resId = getResources().getIdentifier("charge_" + chargePlug,
// "string", this.getPackageName());
//String charge = getString(resId);
if (mTextViewLevel!=null) mTextViewLevel.setText(""+level+"%");
if (mTextViewTemperature!=null) mTextViewTemperature.setText(temperature+"°C");
if (mTextViewVoltage!=null) mTextViewVoltage.setText(voltage+"mV");
if (mTextViewHealth!=null) mTextViewHealth.setText(health);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment