Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Firemonkey enable GPS service for Android

I was wandering if you can enable the GPS service in a Firemonkey project? The locationsensor doesn't enable it. It can only get GPS coordinates if GPS is enabled or you have a network location.

In some other Android apps it asks if you want to enable the GPS, and if you agree it will enable GPS for that app. I also want to do this.

I already know how to check if GPS service is enabled for Android, but not how to enable it itself.

Code below is how to check if GPS is enabled:

uses
  Androidapi.JNI.Location,
  Androidapi.JNIBridge,
  FMX.Helpers.Android,
  Androidapi.JNI.GraphicsContentViewText;

{$R *.fmx}

procedure TForm1.Button1Click(Sender: TObject);
var
  locationManager : JLocationManager;
begin
  locationManager := TJLocationManager.Wrap( ((SharedActivity.getSystemService(TJContext.JavaClass.LOCATION_SERVICE)) as ILocalObject).GetObjectID);

  if locationManager.isProviderEnabled(TJLocationManager.JavaClass.GPS_PROVIDER) then
   ;   //do something   

  if locationManager.isProviderEnabled(TJLocationManager.JavaClass.NETWORK_PROVIDER) then 
   ;   //do something  else
end;

I've tried to do the same if you would program it in Java. Like this link: https://stackoverflow.com/a/5305835/2728408

procedure TForm1.Button1Click(Sender: TObject);
{$IFDEF ANDROID}
var
  Intent: JIntent;
{$ENDIF}
begin
{$IFDEF ANDROID}
  Intent := TJIntent.Create;
  Intent.addCategory(TJIntent.JavaClass.CATEGORY_ALTERNATIVE);
  Intent.setData(TJnet_Uri.JavaClass.parse(StringToJString('3')));
  Intent.setClassName(StringToJString('com.android.settings'), StringToJString('com.android.settings.widget.SettingsAppWidgetProvider'));
  try
    //For Delphi 10 Seattle
    TAndroidHelper.Activity.sendBroadcast(Intent);
    //For older versions of Delphi
    //SharedActivity.sendBroadcast(Intent);
  except
    on e: exception do
    begin
      ShowMessage('Error: ' + e.Message);
    end;
  end;
{$ENDIF}
end;

I don't get any error but my GPS also doesn't get turned on.

UPDATE: It seems to be disabled to enable GPS for Android 4.0 and higher.

like image 933
Remi Avatar asked Sep 05 '25 03:09

Remi


1 Answers

You can't enable GPS, but you can ask user to do it:

procedure TForm1.GPSSettings;
{$IFDEF ANDROID}
var
  Intent: JIntent;
{$ENDIF}
begin
{$IFDEF ANDROID}
  Intent := TJIntent.Create;
  Intent :=     TJIntent.JavaClass.init(TJSettings.JavaClass.ACTION_LOCATION_SOURCE_SETTINGS);
  TAndroidHelper.Activity.startActivity(Intent);
{$ENDIF}
end;
like image 121
Rusland Avatar answered Sep 07 '25 19:09

Rusland