User:Maria/Mobile Tutorial: Creating Local Android Services

From RAD Studio
Jump to: navigation, search

Go Up to Mobile Tutorials: Mobile Application Development (iOS and Android)


This tutorial describes how to create a Multi-Device application with two local Android services.

The StartService project shows how to start a service using TLocalServiceConnection.StartService(<service_name>).

The BindService project shows how to bind to a service using TLocalServiceConnection.BindService(<service_name>), and how to unbind from a service using TLocalServiceConnection.UnBindService.

Create the StartService Project

The StartService Android Service will be started by the main application using TLocalServiceConnection.StartService('StartService').

Once StartService is started, the OnStartCommand event is triggered. A procedure will start with an anonymous thread and procedure with a for loop that writes lines into Logcat. The service stops itself when the loop finishes.

  1. Go to File > New > Other, then navigate to:
    • Delphi projects > Android Service.
  2. In the New Android Service wizard, select Local Service.
  3. Click OK. The project is added to the Project Manager.
  4. Change the project name to StartService.
    Note: The project name is the name of the service.
  5. Save the project:
    • The unit as UStartService.pas.
    • The Delphi project as StartService.dproj.

As our example has more than one service, you need to have exclusive names for the different services:

  • Service name. The name of the project.
  • Unit name. The name of the .pas file.
  • The Data Module name:
    • On the Object Inspector, Edit the property Name of the Data Module to StartServiceDM.

Editing the StartService Data Module

Open the Data Module to create the procedure that writes lines into Logcat.

  • On the Project Manager, double-click UStartService.dfm to open the data module on the code editor.

Create the following procedure:

type
  TStartServiceDM = class(TAndroidService)
  private
    { Private declarations }
    FThread: TThread;
    procedure Test;
procedure TStartServiceDM.Test;
var
  M: TMarshaller;
begin
  FThread := TThread.CreateAnonymousThread(
    procedure
    var
      I: Integer;
    begin
      for I := 0 to 1000 do
      begin
        LOGW(M.AsUtf8('Counter: ' + I.ToString).ToPointer);
        Sleep(1000);
      end;
      JavaService.stopSelf;

    end);

  FThread.Start;
end;
function TStartServiceDM.AndroidServiceStartCommand(const Sender: TObject;
  const Intent: JIntent; Flags, StartId: Integer): Integer;
begin
  Result := TJService.JavaClass.START_STICKY;
  Test;
end;

Add the following units to the uses section:

AndroidApi.Log, AndroidApi.JNI.App;

Create the BindService Project