How to get the battery percentage?

6

How do I get the battery percentage and report on a battery-style chart?

    
asked by anonymous 11.09.2015 / 03:40

1 answer

6

I will partially answer your question.

To recover the battery level, you need to fire an Intent-Filter to ACTION_BATTERY_CHANGED . Below is an example code that, also, sets a BroadCastReceiver to run when Intent is fired.

//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 < br> Suggested Reading: BatteryManager

    
11.09.2015 / 04:31