-1

I'm using Delphi 10.3 for developing android application and I have implemented Service to retrieve the data from Server. The thread was running properly but it closes when the app is closed. I have used the following code to run the service:

DMService.StartCommand();
begin
  AddLog; //Log 
  SampleThread :=  TThread.Create;
  Result := TJService.JavaClass.START_REDELIVER_INTENT;
end;

The same code worked fine in Delphi 10.1 (without mentioning the Android 26 as target version).

Also I have tried using TTask but still the problem does not resolves. Also I have tried Result := TJService.JavaClass.START_STICKY;, but still the service closes.

And after several analysis, I have analyzed after closing the host application the service, the Service starts again and the thread/Task initiated and the service was destroyed.

Should I need to enable any special permission or while creating should I need to add more code. Currently, I'm using the following code for initiating the service from the host application:

  FLocalServiceConnection := TLocalServiceConnection.Create;
  FLocalServiceConnection.StartService('SCommuteSupervisorNotificationService');

Please help me to resolve this issue to run the service after the host app closes.

Dev123Dev
  • 31
  • 2
  • It's likely due to background execution limits: https://developer.android.com/about/versions/oreo/background. The service needs to be in the foreground when the app moves into the background or is stopped. There is an example how to do this in the TServiceModule.StartForeground method in this unit: https://github.com/DelphiWorlds/KastriFree/blob/master/Demos/AndroidLocation/Service/LS.ServiceModule.pas. The main problem is that a persistent notification appears to the user when the service is in the foreground. Apps should use a JobIntentService, which sadly is yet to be supported in Delphi. – Dave Nottage Apr 28 '19 at 20:18
  • Thanks a lot Dave – Dev123Dev May 02 '19 at 18:14

1 Answers1

2

This code works for me

procedure TDM.StartForeground;
var
  LBuilder: JNotificationCompat_Builder;
begin
  try
    //if FIsForeground or not TAndroidHelperEx.CheckBuildAndTarget(26) then
      //Exit; // <======
    LBuilder := TJNotificationCompat_Builder.JavaClass.init(TAndroidHelper.Context);
    LBuilder.setAutoCancel(True);
    LBuilder.setContentTitle(StrToJCharSequence('Sample'));
    LBuilder.setContentText(StrToJCharSequence('Monitoring location changes'));
    LBuilder.setSmallIcon(TAndroidHelper.Context.getApplicationInfo.icon);
    LBuilder.setTicker(StrToJCharSequence('Sample 2'));
    TJService.Wrap(System.JavaContext).startForeground(3987, LBuilder.build);
  except

  end;
end;

function TDM.AndroidServiceStartCommand(const Sender: TObject;
  const Intent: JIntent; Flags, StartId: Integer): Integer;
begin  
  StartForeground;
  Result := TJService.JavaClass.START_STICKY;
end;
Dev123Dev
  • 31
  • 2