1

我正在尝试在某个代码后更换电池。我正在使用以下代码,但不幸的是没有运气。我得到零任何想法请

在上创建一个:

batteryIntent = registerReceiver(null,new IntentFilter(Intent.ACTION_BATTERY_CHANGED));

private double batteryLevel() {
   int rawlevel = batteryIntent.getIntExtra("level", -1);
   double scale = batteryIntent.getIntExtra("scale", -1);
   double level = -1;
   if (rawlevel >= 0 && scale > 0) {
       level = rawlevel / scale;

   }
return level;

 } 

在 onClick 上:

double startbatterylevel = batteryLevel();

//certain code

double estimatedbattery  =  startbatterylevel -  endbatterylevel ;
Estbatterylevel.setText("estimated battery"+estimatedbattery);
4

2 回答 2

3

如您所写,我们不知道问题出在电池电量检测方法还是减法上。该方法的输出是什么batteryLevel();?它是准确的还是始终是默认值?

您可以尝试调整此页面上的示例:http: //mobiledevtuts.com/android/android-sdk-get-device-battery-information/

public void onCreate(Bundle savedInstanceState) {
    ...
    this.registerReceiver(this.batteryInfoReceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
    ...
}

private BroadcastReceiver batteryInfoReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        int level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, 0);
        Estbatterylevel.setText("estimated battery" + level);
    }
};

如果仍然显示 0,则可能存在兼容性问题。你能提供你的设备规格和安卓版本吗?

于 2012-11-29T09:56:15.437 回答