请查看this文章。Daniele Spinetti使用服务中的LocationSensor解决问题。
将System.Sensors和System.Android.Sensors单元添加到您的项目中并进行更改(Delphi 10 Seattle)。
System.Sensors.pas
implementation
uses
System.Variants, System.Math, System.Character,
{$IFDEF ANDROID}
System.Android.Sensors;
{$ENDIF ANDROID}
System.Android.Sensors.pas
uses
System.Sensors;
...
class constructor TPermission.Create;
var
PackageInfo: JPackageInfo;
PackageManager: JPackageManager;
Activity: JActivity;
LContext: JContext;
begin
LContext := TJContextWrapper.Wrap(System.JavaContext);
PackageManager := LContext.getPackageManager();
PackageInfo := PackageManager.getPackageInfo
(LContext.getApplicationContext.getPackageName,
TJPackageManager.JavaClass.GET_PERMISSIONS);
FPermissions := PackageInfo.requestedPermissions;
end;
...
type
TAndroidGeocoder = class(TGeocoder)
private type
TGeocoderRunnable = class(TJavaLocal, JRunnable)
private
FCoord: TLocationCoord2D;
FLGeocoder: JGeocoder;
public
constructor Create(ACoord: TLocationCoord2D; AGeocoder: JGeocoder);
procedure run; cdecl;
end;
private
class var
FGeocoder: JGeocoder;
FActivity: JContextWrapper;
...
TUIAndroidLocationSensor = class(TCustomLocationSensor)
private
FPermitted: Boolean;
FActivity: JContext;
FLastValue: JLocation;
FLocationManager: JLocationManager;
FAccuracy: TLocationAccuracy;
...
constructor TUIAndroidLocationSensor.Create(AManager: TSensorManager);
var
LocationService: JObject;
begin
inherited;
FActivity := TJContext.Wrap(System.JavaContext);
LocationService := FActivity.getSystemService
(TJContext.JavaClass.LOCATION_SERVICE);
if Assigned(LocationService) then
FLocationManager := TJLocationManager.Wrap((LocationService as ILocalObject)
.GetObjectID);
end;
...
function RunIfPossible(var ARunnable: TLocationRunnable;
var AListener: TLocationListener; AProviderName: JString): Boolean;
var
Provider: JLocationProvider;
LHandler: JHandler;
begin
Result := False;
if FLocationManager.isProviderEnabled(AProviderName) then
begin
if AListener = nil then
AListener := TLocationListener.Create(Self);
Provider := FLocationManager.getProvider(AProviderName);
if Provider <> nil then
begin
ARunnable := TLocationRunnable.Create(FLocationManager, AListener,
AProviderName);
LHandler := TJHandler.JavaClass.init;
LHandler.post(ARunnable);
Result := True;
end;
end;
end;
...
class constructor TAndroidGeocoder.Create;
begin
FActivity := TJContextWrapper.Wrap(System.JavaContext);
FGeocoder := TJGeocoder.JavaClass.init(FActivity);
end;
然后你可以像这样使用LocationSensor:
uses System.Sensors, System.Android.Sensors;
...
var
FSensors: TSensorArray;
Sensor: TCustomSensor;
begin
TSensorManager.Current.Active := true;
FSensors := TSensorManager.Current.GetSensorsByCategory(TSensorCategory.Location);
FSensor := nil;
for Sensor in FSensors do
begin
if TCustomLocationSensor(Sensor).SensorType = TLocationSensorType.GPS then
begin
FSensor := TCustomLocationSensor(Sensor);
Break;
end;
end;
if not Assigned(FSensor) then
Exit;
if not FSensor.Started then
FSensor.Start;