IPアドレスを取得するAndroidアプリケーションを作成する ~Delphiでお手軽プログラミング
1.Delphiを起動
Delphiを起動して新規FMXプロジェクトを作成し、ターゲットプラットフォームをAndroidに設定して、 フォームにTButtonを1つ、TMemoを1つ配置します。プロジェクトとユニットを保存します。
2.権限設定
権限は、一切不要です。3.ソースコードの記述
Button1ダブルクリックしてソースを記述します。
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.ScrollBox,
FMX.Memo, FMX.Controls.Presentation, FMX.StdCtrls;
type
TForm1 = class(TForm)
Button1: TButton;
Memo1: TMemo;
procedure Button1Click(Sender: TObject);
private
{ private 宣言 }
public
{ public 宣言 }
end;
var
Form1: TForm1;
implementation
uses Androidapi.JNI.Java.Net, //TJNetworkInterface
Androidapi.JNI.JavaTypes, //JEnumeration
Androidapi.Helpers //JObjectToID
;
{$R *.fmx}
procedure TForm1.Button1Click(Sender: TObject);
var NetworkInterfaces:JEnumeration;
NetworkInterface:JNetworkInterface;
IpAddresses:JEnumeration;
IpAddress:JInetAddress;
ClassName:String;
HostAddress:String;
isIPv4:Boolean;
isLoopback:Boolean;
begin
TThread.CreateAnonymousThread(
procedure()
begin
NetworkInterfaces:=TJNetworkInterface.JavaClass.getNetworkInterfaces;
while NetworkInterfaces.hasMoreElements do
begin
NetworkInterface:=
TJNetworkInterface.Wrap(JObjectToID(NetworkInterfaces.nextElement));
IpAddresses:=NetworkInterface.getInetAddresses;
while IpAddresses.hasMoreElements do
begin
//アドレス情報の取得
IpAddress:=TJInetAddress.Wrap(JObjectToID(IpAddresses.nextElement));
//IPv4かIPv6か
ClassName:=JStringToString(IpAddress.getClass.getName);
if ClassName.Contains('Inet6Address') then
isIPv4:=False
else
isIPv4:=True;
//ループバックアドレス(127.0.0.1)か
isLoopback:=IpAddress.isLoopbackAddress;
//アドレスの取得
HostAddress:=JStringToString(IpAddress.getHostAddress);
//IPv6の場合
if not isIPv4 then
begin
//%の文字までに整形する
HostAddress:=HostAddress.Substring(0,HostAddress.IndexOf('%'));
end;
TThread.Synchronize(TThread.CurrentThread,
procedure
begin
if not isLoopback then //ループバックを出力しない場合
if isIPv4 then //IPv4だけを出力する場合
begin
memo1.Lines.Add(HostAddress);
memo1.GoToTextEnd;
end;
end);
end;
end;
end).Start;
end;
end.
