How to get the battery percentage?

Asked

Viewed 1,106 times

6

How to take the battery percentage and report on a battery-style chart?

1 answer

6


I’ll partially answer your question.

To regain battery level, you need to fire an Intent-Filter to ACTION_BATTERY_CHANGED. Below is an example of code that also programs a BroadCastReceiver to be executed when the Intent is triggered.

//Método responsável para descobrir o nível da bateria
private void batteryLevel(){
    //Cria o broadcastreceiver
    BroadcastReceiver batteryLevelReceiver = new BroadcastReceiver(){

        //Método executado sempre que o broadcast for executado
        public void onReceive(Context context, Intent  intent){             
            context.unregisterReceiver(this);
            //pega nível da bateria da intent
            int rawLevel = intent.getIntExtra("level", -1);

            //pega o nível máximo da bateria
            int scale = intent.getIntExtra("scale", -1);
            int level = -1;

            if(rawLevel >= 0 && scale > 0){
            //faz o cálculo do percentual.
            level = (rawLevel *100)/scale;
            }
        }
    }
};

//Cria um intent filter para a classe BATTERY_CHANGED.
//Em BATTERY_CHANGED você tem acesso a outras informações sobre a bateria.
IntentFilter batteryLevelFilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);;
registerReceiver(batteryLevelReceiver, batteryLevelFilter);

Source: techne.cesar.org.br
Reading suggestion: Batterymanager (in English)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.