I wrote a function in a Delphi Android app to determine if either Mobile or Wifi (or both) are enabled. I used Checking internet connection in android using getActiveNetworkInfo for reference.
I must have made a mistake, because the function isn't detecting Wifi, even when it is enabled on the phone!
function WhichNetwork: Integer; // 0 = none, 1 = wifi only, 2 = mobile only, 3 = both
var
obj: JObject;
cm: JConnectivityManager;
networks: TJavaObjectArray<JNetwork>;
i: Integer;
network: JNetworkInfo;
networktype: Integer;
networkname: String;
begin
Result := 0;
obj := TAndroidHelper.Context.getSystemService(TJContext.JavaClass.CONNECTIVITY_SERVICE);
if Assigned(obj) then
begin
cm := TJConnectivityManager.Wrap((obj as ILocalObject).GetObjectID);
if Assigned(cm) then
begin
networks := cm.getAllNetworks;
if Assigned(networks) then
begin
for i := 0 to networks.Length - 1 do // this looks right!
begin
network := cm.getNetworkInfo(i);
networkname := JStringtoString(network.getTypeName); // for debug
networktype := network.gettype;
if networkType = TJConnectivityManager.JavaClass.TYPE_MOBILE then
begin
if network.isConnectedOrConnecting then
Result := Result + 2;
end
else if networkType = TJConnectivityManager.JavaClass.TYPE_WIFI then
begin
if network.isConnectedOrConnecting then
Result := Result + 1;
end;
end;
end;
end;
end;
end;
After experimenting, I made the following change and it worked!
for i := 0 to networks.Length do // now this works
But, this is so not how Delphi usually works. Can someone explain why the Length
of a TJavaObjectArray
is zero-based?
It's an academic question, and I really want to understand this.