我一直在嘗試使用Delphi Seattle編寫一個Android服務,但每次應用程序崩潰並停止響應。我的服務需要使用UDP連接將消息發送到服務器。Delphi中的Android服務
這是我寫的一個簡單例子。
主機應用
unit Unit3;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs,
FMX.Controls.Presentation, FMX.StdCtrls, System.Android.Service;
type
TForm3 = class(TForm)
Start: TButton;
procedure StartClick(Sender: TObject);
private
{ Private declarations }
ConexaoServico : TLocalServiceConnection;
public
{ Public declarations }
end;
var
Form3: TForm3;
implementation
{$R *.fmx}
procedure TForm3.StartClick(Sender: TObject);
begin
ConexaoServico := TLocalServiceConnection.Create;
ConexaoServico.StartService('Servicoteste');
end;
end.
服務
unit AndroidServicoteste;
interface
uses
System.SysUtils,
System.Classes,
System.Android.Service,
AndroidApi.JNI.GraphicsContentViewText,
Androidapi.JNI.Os, IdBaseComponent, IdComponent, IdUDPBase, IdUDPClient;
type
TAndroidServiceDM = class(TAndroidService)
IdUDPClient1: TIdUDPClient;
function AndroidServiceStartCommand(const Sender: TObject;
const Intent: JIntent; Flags, StartId: Integer): Integer;
private
{ Private declarations }
public
{ Public declarations }
end;
var
AndroidServiceDM: TAndroidServiceDM;
implementation
{%CLASSGROUP 'FMX.Controls.TControl'}
{$R *.dfm}
uses
Androidapi.JNI.App;
function TAndroidServiceDM.AndroidServiceStartCommand(const Sender: TObject;
const Intent: JIntent; Flags, StartId: Integer): Integer;
begin
IdUDPClient1.Connect;
IdUDPClient1.Send('Teste', nil);
IdUDPClient1.Host:= '192.168.1.109';
IdUDPClient1.Port:= 45001;
Result:= TJService.JavaClass.START_STICKY;
end;
end.
當我按下啓動(TButton的),我什麼也得不到的服務器。
任何幫助,將不勝感激。
在調用IdUDPClient1.Connect和IdUDPClient1.Send('Teste',nil)之前,您不應該分配'IdUDPClient1.Host'和'IdUDPClient1.Port'嗎? –
是的,您需要在調用Connect()之前分配'Host' /'Port'屬性。另一方面,你並不需要首先使用Connect(),你可以直接將'Host' /'Port'值直接傳遞給'Send()':'IdUDPClient1.Send('192.168 .1.109',45001,'Teste',nil);' –
請注意,['onStartCommand']的Android文檔(http://developer.android.com/reference/android/app/Service.html#onStartCommand%28android .content.Intent,%20int,%20int%29)警告:「*請注意,系統會在您的服務的主線程上調用此服務的主線程與在同一進程中運行的活動發生UI操作的線程相同。你應該總是避免拖延主線程的事件循環,當進行長時間運行的操作時,**網絡調用**或繁重的磁盤I/O,你應該**啓動一個新的線程,或者使用AsyncTask **。*「 –