If you think the Android project CalWatch listed in this page is inappropriate, such as containing malicious code/tools or violating the copyright, please email info at java2s dot com, thanks.
Java Source Code
/*
* CalWatch//fromwww.java2s.com
* Copyright (C) 2014 by Dan Wallach
* Home page: http://www.cs.rice.edu/~dwallach/calwatch/
* Licensing: http://www.cs.rice.edu/~dwallach/calwatch/licensing.html
*/package org.dwallach.calwatch;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.BatteryManager;
import android.util.Log;
/**
* Created by dwallach on 9/1/14.
*/publicclass BatteryWrapper {
privatestaticfinal String TAG = "BatteryWrapper";
private Context context;
privateint status;
privateboolean isCharging;
privateint chargePlug;
privateboolean usbCharge;
privateboolean acCharge;
privatefloat batteryPct = 1.0f;
privatestatic BatteryWrapper singleton;
private BatteryWrapper(Context context) {
this.context = context;
singleton = this;
}
publicstaticvoid init(Context context) {
if(singleton == null) {
singleton = new BatteryWrapper(context);
} elseif (context != singleton.context) {
Log.v(TAG, "Hmm, a new context");
singleton.context = context;
}
singleton.fetchStatus();
}
publicstatic BatteryWrapper getSingleton() {
if(singleton == null)
Log.e(TAG, "BatteryWrapper not initialized properly");
return singleton;
}
publicvoid fetchStatus() {
// and now, some code for battery measurement, largely stolen from the
// official docs.
// http://developer.android.com/training/monitoring-device-state/battery-monitoring.html
try {
IntentFilter ifilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
Intent batteryStatus = context.registerReceiver(null, ifilter);
// Are we charging / charged?
status = batteryStatus.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
isCharging = (status == BatteryManager.BATTERY_STATUS_CHARGING || status == BatteryManager.BATTERY_STATUS_FULL);
// How are we charging?
chargePlug = batteryStatus.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1);
usbCharge = chargePlug == BatteryManager.BATTERY_PLUGGED_USB;
acCharge = chargePlug == BatteryManager.BATTERY_PLUGGED_AC;
int level = batteryStatus.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
int scale = batteryStatus.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
batteryPct = level / (float) scale;
} catch (Throwable throwable) {
// if something fails, we really don't care; whatever value as in batteryPct from
// last time is just fine for the next time
}
}
publicfloat getBatteryPct() {
return batteryPct;
}
publicboolean getIsCharging() {
return isCharging;
}
}