My app done with Delphi 10.3 is starting and monitoring my android service successfully on Android version 7. But above Android Version 8 I get error:
java.lang.IllegalStateException: Not allowed to start Intent ... app is in background uid null
Found that from Version 8 Android has changed policies. I should use startForegroundService but then is me unclear how to respond from service to notify Android and allow to start. (And cannot found Delphi sample example)
Here the start service code
procedure TfrmStarter.StartBLEService;
var
Intent : JIntent;
NativeComponent : JComponentName;
PackageName, AppName : JString;
begin
PackageName := StringToJString('com.embarcadero.LysaAdmin');
AppName := StringToJString('com.embarcadero.services.BLEService');
Intent := TJIntent.Create;
Intent.setAction(TJIntent.JavaClass.ACTION_MAIN);
Intent.addCategory(TJIntent.JavaClass.CATEGORY_LAUNCHER);
NativeComponent := TJComponentName.JavaClass.init(PackageName, AppName);
Intent.addFlags(TJIntent.JavaClass.FLAG_ACTIVITY_NEW_TASK or TJIntent.JavaClass.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
Intent.setComponent(NativeComponent);
SharedActivity.startService(Intent); //<< This work's fine Android 7
// SharedActivity.startForegroundService(Intent); //<< Android 8.1 not getting errors but service is not started
end;
Service StartCommand code
function TDM.AndroidServiceStartCommand(const Sender: TObject;
const Intent: JIntent; Flags, StartId: Integer): Integer;
begin
Result := TJService.JavaClass.START_STICKY;
end;
Delphi provides the ability to start a service in one line
uses System.Android.Service;
...
TLocalServiceConnection.StartService('service_name');
service_name - just service name, without package (com.embarcadero. )!