android获取电池信息;android获取电池容量、技术、电压、电量、温度等信息
public class BatteryUtil {
private static final String TAG = "BatteryUtil";
private static String technology;
private static int voltage;
private static int level;
private static double temperature;
private static String status;
private static String health;
private static String plugged;
public static String getBatteryCapacity(Context context) {
Object mPowerProfile;
double batteryCapacity = 0;
final String POWER_PROFILE_CLASS = "com.android.internal.os.PowerProfile";
try {
mPowerProfile = Class.forName(POWER_PROFILE_CLASS)
.getConstructor(Context.class)
.newInstance(context);
batteryCapacity = (double) Class
.forName(POWER_PROFILE_CLASS)
.getMethod("getBatteryCapacity")
.invoke(mPowerProfile);
} catch (Exception e) {
e.printStackTrace();
}
return String.valueOf(batteryCapacity);
}
public static void ReceiverBatteryOhterInfo(Context context) {
IntentFilter filter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
Intent receiver = context.registerReceiver(null, filter);
technology =receiver.getStringExtra("technology");
if(technology.equals("") || technology.equals(null)){
technology="Unknown";
}
voltage = receiver.getIntExtra("voltage", 0);
level = receiver.getIntExtra("level", 0);
temperature = receiver.getIntExtra("temperature", 0)/10.0;
switch (receiver.getIntExtra("status",0)){
case BatteryManager.BATTERY_HEALTH_UNKNOWN:
status="未知";
break;
case BatteryManager.BATTERY_STATUS_CHARGING:
status="充电中";
break;
case BatteryManager.BATTERY_STATUS_DISCHARGING:
status="放电中";
break;
case BatteryManager.BATTERY_STATUS_NOT_CHARGING:
status="未充电";
break;
case BatteryManager.BATTERY_STATUS_FULL:
status="电池满";
break;
}
android.util.Log.d(TAG,"status:"+status);
switch (receiver.getIntExtra("health",0)){
case BatteryManager.BATTERY_HEALTH_UNKNOWN:
health="未知";
break;
case BatteryManager.BATTERY_HEALTH_GOOD:
health="良好";
break;
case BatteryManager.BATTERY_HEALTH_OVERHEAT:
health="过热";
break;
case BatteryManager.BATTERY_HEALTH_DEAD:
health="没电";
break;
case BatteryManager.BATTERY_HEALTH_OVER_VOLTAGE:
health="过电压";
break;
case BatteryManager.BATTERY_HEALTH_COLD:
health="温度过低";
break;
case BatteryManager.BATTERY_HEALTH_UNSPECIFIED_FAILURE:
health="未知错误";
break;
}
android.util.Log.d(TAG,"health:"+health);
switch (receiver.getIntExtra("plugged",0)){
case BatteryManager.BATTERY_PLUGGED_AC:
plugged="充电器";
break;
case BatteryManager.BATTERY_PLUGGED_USB:
plugged="USB";
break;
case BatteryManager.BATTERY_PLUGGED_WIRELESS:
plugged="无线充电";
break;
default:
plugged="未充电";
break;
}
android.util.Log.d(TAG,"plugged:"+plugged);
}
}
参考:https://blog.csdn.net/su749520/article/details/80655708
|