首页 > 解决方案 > 尝试在前台启动时出现 Android 服务段错误

问题描述

我试图对如何在前台启动最基本的android服务有一个基本的了解。我查看了 Location Foreground 示例和多个在线帖子,但似乎没有一个只是给出一个基本而直接的示例,以便我可以理解基础知识。

据我了解,要让服务在前台运行,它必须显示一个持续的通知,以便用户知道该服务正在后台运行。

我可以在 StartCommand 事件中使用以下内容成功启动服务:

 Result := TJService.JavaClass.START_STICKY;
// Some code that shows a notification with the NotificationCenter Component to indicate a successful start.

现在我正试图让它在前台运行。

在服务创建事件中,我正在创建通知通道:

var
  NotificationChannel := NotificationCenter.CreateChannel;
  NotificationChannel.Id := 'foreground_service';
  NotificationChannel.Title := 'Foreground test';
  NotificationChannel.Importance := TImportance.Default;

  NotificationCenter.CreateOrUpdateChannel(NotificationChannel);

 FNotificationManager := TJNotificationManager.Wrap
    (TAndroidHelper.Context.getSystemService
    (TJContext.JavaClass.NOTIFICATION_SERVICE));

主应用程序上有 2 个按钮。一个启动服务,一个停止服务。

开始按钮:

 dmService.StartForeground;
procedure TdmService.StartForeground;
begin
  var
  ntf := TJNotificationCompat_Builder.JavaClass.init(TAndroidHelper.Context,
    StringToJString('foreground_service'));

  ntf.setSmallIcon(TAndroidHelper.Context.getApplicationInfo.icon);

  var
  aNtf := ntf.build;

  JavaService.StartForeground(-1, aNtf); // Causes a segment Fault
  FNotificationManager.notify(-1, aNtf);
end;

为什么它会导致段错误,我该如何避免这种情况?即使应用程序打开,我也希望服务继续运行,因此基于绑定和解除绑定启动和停止服务不是我想做的事情。

标签: androiddelphiandroid-service

解决方案


推荐阅读