How to find out the percentage of battery charge in Android? Here is the code I used:

registerReceiver(new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { Info.this.batteryLevel = intent.getIntExtra("level", -1); } }, new IntentFilter(Intent.ACTION_BATTERY_CHANGED)); 

as a result of which the value of the variable batteryLevel is 1134231552. Instead of "level" I tried to specify BatteryManager.EXTRA_LEVEL - the result is the same, each time there are such strange large numbers. How to fix the error?


I also tried to get the battery charge value like this:

 Info.this.batteryLevel = (float) intent.getIntExtra("level", -1) / (float) intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1); 

the result is the same.

    2 answers 2

    Here is a link to get information on how to get information about the battery link

     public class Main extends Activity { private TextView batteryTxt; private BroadcastReceiver mBatInfoReceiver = new BroadcastReceiver(){ @Override public void onReceive(Context ctxt, Intent intent) { int level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, 0); batteryTxt.setText(String.valueOf(level) + "%"); } }; @Override public void onCreate(Bundle b) { super.onCreate(b); setContentView(R.layout.main); batteryTxt = (TextView) this.findViewById(R.id.batteryTxt); this.registerReceiver(this.mBatInfoReceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED)); } } 

      We must also request a scale:

       int scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1); 

      level is measured as (float)level/(float)scale

      • Changed the question. - nick