android - 尝试在前台启动时出现 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;
为什么它会导致段错误,我该如何避免这种情况?即使应用程序打开,我也希望服务继续运行,因此基于绑定和解除绑定启动和停止服务不是我想做的事情。
解决方案
推荐阅读
- python - 使用 python 从自定义路径验证 SSL 证书
- angular - Angular - 使用子路由延迟加载模块内部的模块
- angular - 如何使用 @ViewChild() 在 Angular 库之外调用 Angular 组件方法?
- servlets - AEM Servlet 未执行
- c++ - 使用指针指向 Vector 的索引,C++
- .net-core - 如何将边界框信息叠加到 JPG 上并创建 PDF
- python - 问:如何存储/保存 Pylint 执行的结果?
- mysql - MySQL如何按列分组并使某些值进入1行
- wordpress - 无法通过移动浏览器访问本地主机上的 Wordpress 站点(Chrome devtools - 远程设备)
- react-native - React Native - 如何将捕获的图像存储在应用程序中,而不是存储在图库中并将它们从应用程序本身上传到 AWS s3