LoginSignup
2
1

More than 5 years have passed since last update.

Delphi で Android 端末のバッテリーレベルを特定する

Posted at

バッテリーの充電レベルを知りたいことってありますよね。
Android では BatteryManager によってバッテリーに関する情報がインテントでブロードキャストされています。

充電レベルを調べるには、バッテリーレベル(level)と、段階(scale)を取り出して、%を計算します。
このコードは、Android Developersのトレーニング記事「バッテリー レベルと充電状態を監視する」を参考にしています。

サンプルコード

フォーム上にボタンとリストボックスを置き

  • ボタンを押すと充電レベルを検出する
  • 検出した%の値をリストボックスに書き出す

という処理を記述しています。(10.2 Tokyo, Nexus 5, Android 5.1.1で確認)

unit Unit1;

interface

uses
  System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
  FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs,
  FMX.Controls.Presentation, FMX.StdCtrls, FMX.Layouts, FMX.ListBox,
  Androidapi.Helpers, Androidapi.JNI.GraphicsContentViewText,
  Androidapi.JNI.JavaTypes
  ;

type
  TForm1 = class(TForm)
    ListBox1: TListBox;
    Button1: TButton;
    procedure Button1Click(Sender: TObject);
  private
    { private 宣言 }
  public
    { public 宣言 }
  end;

var
  Form1: TForm1;

implementation

{$R *.fmx}

procedure TForm1.Button1Click(Sender: TObject);
var
  ifl: JIntentFilter;
  ctx: JContext;
  bStatus: JIntent;
  level, scale: Integer;
begin
  // 現在の充電状態を特定(バッテリーステータス インテントを取得)
  ifl := TJintentFilter.JavaClass.init(TJIntent.JavaClass.ACTION_BATTERY_CHANGED);
  ctx := TAndroidHelper.Context;
  bStatus := ctx.registerReceiver(nil, ifl);

  // BatteryManager.EXTRA_LEVEL の実態は levelという文字列
  // BatteryManager.EXTRA_SCALE の実態は scaleという文字列
  level := bStatus.getIntExtra(StringToJString('level'), -1);
  scale := bStatus.getIntExtra(StringToJstring('scale'), -1);

  ListBox1.Items.Add('Battery');
  // 充電状態の %を計算
  ListBox1.Items.Add(IntToStr((100*level) div scale));
end;

end.

2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1