Search code examples
androiddelphifiremonkeydelphi-xe6

Firemonkey Android get battery level


I got a function:

function BatteryPercent(const aContext: JContext): Integer;
var
  filter: JIntentFilter;
  battery: JIntent;
  level, scale: Integer;
begin
  filter := TJIntentFilter.Create;
  filter.addAction(TJIntent.JavaClass.ACTION_BATTERY_CHANGED);

  battery := aContext.registerReceiver(NIL, filter);
  level := battery.getIntExtra(StringToJString('level'), -1);
  scale := battery.getIntExtra(StringToJString('scale'), -1);

  result := (100 * level) div scale;
end;

But what should I pass as aContext param?

I need to get battery life every minute and save it to memo...


Solution

  • You can read this article on my Blog; "Battery Information (Android - XE5)". The original Article is in Spanish, but you can try automatic translation (on right of page).

    You can read the code and download the sample project (with sources).

    The code I use is similar to this:

      // Contexto
      myContext := SharedActivityContext;
    
      // Creamos y Configuramos el Intent
      filter := TJIntentFilter.Create;
      // Asociamos la ACTION que queremos capturar
      filter.addAction(TJIntent.JavaClass.ACTION_BATTERY_CHANGED);
      // lo registramos
      intentBatt := myContext.registerReceiver(nil, filter);
    

    enter image description here

    Regards.