-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.

4

1 回答 1

2

这段代码对我有用

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;
于 2019-05-02T18:14:19.310 回答