简体   繁体   中英

get battery level on Android after specfic code

I am trying to get the battery change after a certain code. I am using the following code but unfortunately with no luck. I am getting zeros any ideas please

on the on create a:

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;

 } 

and on the onClick:

double startbatterylevel = batteryLevel();

//certain code

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

as you wrote it, we don't know if the problem is in the battery level detection method or in the subtraction. What is the output of the batteryLevel(); method? Is it accurate or always a default value?

You can try to adapt the example on this page: 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);
    }
};

If it is still showing 0, maybe there are compatibility issues. Can you provide your device specifications and android version ?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM