2016-05-15 56 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

相關問題