2016-05-15 181 views
1

我在同一个进程中有一个Android应用程序和服务。在RAD Studio Delphi 10.1下编写代码。从Delphi中的Android服务写入SQLite数据库(RAD Studio)

我需要获得Android服务(我做得很好)的地理坐标并将它们写入SQLite数据库。 有时,应用程序可以(当用户需要时)处理用户界面中的坐标。当我将TConnection(任何 - ADO,FireDAC,UniDAC)放入DataModule中时,甚至不会进行活动连接,即使不运行OnStartCommand事件,该服务也会停止工作。

Monitor.bat显示没有明显错误。

请告诉我如何在Android Service及其Android应用程序中同时使用SQLite数据库。

+0

如果您希望您的Sqlite位于Android设备上,那么您需要一个在Android上运行的Sqlite版本(如果存在)。 ADO是Windows-only afaik,顺便说一句。另一种方式可能是编写一个Windows托管的REST服务器,并让您的Android应用程序写入该服务器。 – MartynA

+0

那么,如果主应用程序关闭,我可以做些什么,但它的服务正在运行?如果我将消息从服​​务发送到应用程序(如Intent或其他人),应用程序将运行,而我不需要它。 –

回答

1

我找到了一个解决方案:

我更新UniDAC组件柏林最新版本(6.3.12)。

TUniConnection和TUniQuery可以很好的与Android Service中的SQLite结合使用。

添加到项目 - >部署主机应用程序我的SQLite DB文件,远程路径设置为“。\ assets \ internal \”。

我希望这段代码对你有用。

procedure TDM.conSQLiteBeforeConnect(Sender: TObject); 
begin 
{$IF DEFINED(iOS) or DEFINED(ANDROID)} 
    conSQLite.Database := TPath.Combine(TPath.GetDocumentsPath, 'mybase.sqlite'); 
{$ENDIF} 
end; 

procedure TDM.conSQLiteError(Sender: TObject; E: EDAError; var Fail: Boolean); 
begin 
    Log('--- DB error: %s:', [E.Message]); 
    Fail := False; 
end; 

function TDM.AndroidServiceStartCommand(const Sender: TObject; const Intent: JIntent; Flags, StartId: Integer): Integer; 
begin 
    Log('+ START with Intent: ' + JStringToString(Intent.getAction.toString), []); 
    if Intent.getAction.equalsIgnoreCase(StringToJString('StopIntent')) then 
    begin 
    try 
     conSQLite.Disconnect; 
     Log('- DB disconnected', []); 
    except 
     on E: Exception do 
     Log('- can not to disconnect DB', [E.Message]); 
    end; 

    Log('... service to be stoped', []); 
    JavaService.stopSelf; 

    Result := TJService.JavaClass.START_NOT_STICKY; // don't reload service 
    end 
    else 
    begin 
    Log('... service started', []); 

    try 
     conSQLite.Connect; 
     Log('+ DB connected', []); 

     UniQuery.SQL.Text := 'select count(*) as ALLREC from orders'; 
     UniQuery.Open; 
     if UniQuery.RecordCount > 0 then 
     begin 
     UniQuery.First; 
     Log('... record count: %s', [UniQuery.FieldByName('ALLREC').AsString]); 
     end; 
     UniQuery.Close; 
    except 
     on E: Exception do 
     Log('- can not to connect DB: %s', [E.Message]); 
    end; 

    Result := TJService.JavaClass.START_STICKY; // rerun service if it stops 
    end; 
end; 
1

我一直在努力了同样的问题,但我开始使用设为TSQLConnection(dbExpress的)组件与TSQLQuery(dbExpress的)组件和这些组件的Android服务工作坚持好。

+0

好消息。你使用哪个版本的RAD Studio? –

+1

我使用Delphi 10.1柏林,但它也是在Delphi 10 Seattle上工作的。 – Lionking