我知道如何将数据发送到远程后台安卓服务:
.
.
FServiceConnection: TRemoteServiceConnection;
.
.
procedure TForm1.Button1Click(Sender: TObject);
const
GET_STRING = 1234;
var
LMessage: JMessage;
begin
FServiceConnection := TRemoteServiceConnection.Create;
FServiceConnection.BindService('Name of the APK containing service', 'Service name');
LMessage := TJMessage.JavaClass.obtain(nil, GET_STRING);
LMessage.replyTo := FServiceConnection.LocalMessenger;
FServiceConnection.ServiceMessenger.send(LMessage);
end;
但是如何为本地Android服务做同样的事情?
.
.
FServiceConnection: TLocalServiceConnection;
.
.
procedure TForm1.Button1Click(Sender: TObject);
const
GET_STRING = 1234;
var
LMessage: JMessage;
begin
FServiceConnection := TLocalServiceConnection.Create;
FServiceConnection.BindService('Service name');
LMessage := TJMessage.JavaClass.obtain(nil, GET_STRING);
????
????
end;
还是有其他方法在应用程序和后台android本地服务之间发送消息吗?
告诉有人这个问题吗?
答案 0 :(得分:0)
我在Android本地服务中使用ServiceStartCommand事件。
按下HOST应用程序活动上的按钮,向服务中发送一个“启动命令”'包含在JIntent中。
procedure TForm3.Button1Click(Sender: TObject);
var
LIntent: JIntent;
begin
Log.D('Try to start');
LIntent := TJIntent.Create;
LIntent.setClassName(TAndroidHelper.Context.getPackageName(),
TAndroidHelper.StringToJString('com.embarcadero.services.SvcTimer'));
LIntent.setAction(StringToJString('StartIntent'));
TAndroidHelper.Activity.startService(LIntent);
end;
该服务获取一个命令并测试我的JIntent,这与一个有什么关系。
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
Log('... service to be stoped', []);
...
JavaService.stopSelf;
Result := TJService.JavaClass.START_NOT_STICKY; // don't reload service
Log('- service stoped', []);
end
else if Intent.getAction.equalsIgnoreCase(StringToJString('StartIntent')) then
begin
...
LocationSensor.Active := True;
Result := TJService.JavaClass.START_STICKY; // rerun service if it stops
Log('+ Service started', []);
end;
end;
所以我们执行主机应用程序命令。
答案 1 :(得分:0)
实际上您可以向本地服务发送消息。 Pax Beach显示的答案会让我的服务崩溃,但如果我只是做我所做的事情,它将会很好地工作:
function TDM.AndroidServiceStartCommand(const Sender: TObject; const Intent: JIntent; Flags, StartId: Integer): Integer;
begin
if (JStringToString(Intent.getAction) = 'StopIntent') then
begin
Result := TJService.JavaClass.START_NOT_STICKY;
JavaService.stopSelf;
Exit;
end;
(....)
end;
答案 2 :(得分:-2)
无法在LocalServices中处理消息...仅在远程服务中处理。
请参阅:http://pt.slideshare.net/jimmckeeth/creating-android-services-with-delphi-and-rad-studio-10-seattle