您可以使用以下方法檢查電池電量
private static int checkBatteryLevel(Context context) {
IntentFilter ifilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
Intent batteryStatus = context.registerReceiver(null, ifilter);
// Are we charging/charged?
int status = batteryStatus.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
boolean isCharging = status == BatteryManager.BATTERY_STATUS_CHARGING || status == BatteryManager.BATTERY_STATUS_FULL;
// If the device is charging then set the state as charging and return.
if (isCharging)
return 100;
// Get the battery level.
int level = batteryStatus.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
int scale = batteryStatus.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
// To get the battery level in %
int batteryLevel = (level * 100)/scale;
Log.e(Constants.TAG, "Battery Level: " + batteryLevel);
return batteryLevel;
}
而且你可以使用下面的接收器來檢測得到連接和斷開
public class BatteryInformationReceiver extends BroadcastReceiver {
private static final String ACTION_POWER_CONNECTED = "android.intent.action.ACTION_POWER_CONNECTED";
private static final String ACTION_POWER_DISCONNECTED = "android.intent.action.ACTION_POWER_DISCONNECTED";
@Override
public void onReceive(Context context, Intent intent) {
String intentAction = intent.getAction();
if (intentAction.equalsIgnoreCase(ACTION_POWER_CONNECTED)) {
} else if (intentAction.equalsIgnoreCase(ACTION_POWER_DISCONNECTED)) {
}
}
}
,並在清單
<receiver android:name="your.package.receivers.BatteryInformationReceiver" >
<intent-filter>
<action android:name="android.intent.action.ACTION_POWER_CONNECTED" />
<action android:name="android.intent.action.ACTION_POWER_DISCONNECTED" />
</intent-filter>
</receiver>
然後,在連接時,計算b使用上述方法進行attery級別。並斷開連接後,計算電池電量。並從時間和電池的價值之間的差異。你可以計算任何你想要的。
希望這會有所幫助