Show/Hide Toolbars

Android Applications

Navigation: Android Specifics > Android "Service"

Basic Remote Service - No Intent

Scroll Prev Top Next More

 

A Remote Service once "Installed" as part of a "Package" be accessed by any Application a RemoteServiceConnection to Bind to the Service referencing a Package Name AND a Service Name.

 

The Host Application need not be running only "Installed".  The Package Name Refers to the host application package and the service name of the service included in that package.

 

const  

PackageName  ='com.embarcadero.RemoteEchoHostApp';

SvcName           = 'com.embarcadero.services.RemoteEchoService';

 

Code

FServiceConnection.BindService(PackageName,SvcName);

 

Where

 FServiceConnection :TRemoteServiceConnection;

 

Communication with Remote Services have to occur via Messages

 

var

 LMessage: JMessage;

const

 GET_STRING = 123;

begin

 LMessage := TJMessage.JavaClass.obtain(nil, GET_STRING);

 LMessage.replyTo := FServiceConnection.LocalMessenger;

 FServiceConnection.ServiceMessenger.send(LMessage);

end;

 

Response

function TRemoteServiceDM.AndroidServiceHandleMessage(const Sender: TObject; const AMessage: JMessage): Boolean;

const

 GET_STRING = 123;

 SERVICE_STRING = 321;

var

 LMessage: JMessage;

 LBundle: JBundle;

begin

 case AMessage.what of

   GET_STRING:

   begin

     LBundle := TJBundle.Create;  // we can not send String because is not parcelable

     LMessage := TJMessage.Create;

     LMessage.what := SERVICE_STRING;

     LBundle.putString(TAndroidHelper.StringToJString('Key'), TAndroidHelper.StringToJString('This is a service text !!!'));

     LMessage.obj := LBundle;

     AMessage.replyTo.send(LMessage);

     Result := True;

   end;

 else

   Result := False;

 end;

end;

 

When debugging the Host Application the "Service"  dpr file is run when the host application or an external application uses a RemoteServiceConnection to Bind to the Service for the first time. Ie nothing happens until the an external or host application triggers the action. As expected when debugging some external application accessing the service you cannot step into the service execution but if you run the host application in Debug mode you can set breakpoints in the service code when the Host application or any External application interacts with the service.

 

 

Examples

https://github.com/Embarcadero/RADStudio10.4Demos/tree/master/Object%20Pascal/Multi-Device%20Samples/Device%20Sensors%20and%20Services/RemoteServiceDemo