android 前台服务权限

q9rjltbz  于 2023-06-20  发布在  Android
关注(0)|答案(1)|浏览(201)

在我的应用程序中,我有一个前台服务,我像这样启动:

  1. reactContext.startService(new Intent(reactContext, MyService.class));

然后在我调用的服务的onCreate中:

  1. startForeground(NOTIFICATION_ID_FOREGROUND, createForegroundNotification("message"));

在阅读了foreground service之后,我注意到如果我的应用程序针对API 28,我必须添加特定的权限:
注:如果目标为API级别28或更高级别的应用尝试创建前台服务而未请求FOREGROUND_SERVICE权限,系统将引发SecurityException。
我没有将此权限添加到我的清单中,并且在服务开始运行时没有收到任何异常。是因为我启动这个服务的方式,因为在文档的示例中,服务是这样启动的:

  1. context.startForegroundService(intent);

我不是做这个的我是否应该添加此权限?

piah890a

piah890a1#

最近面对这个问题。已通过升级目标sdk版本33解决此问题。从这里得到这个参考:https://developer.android.com/develop/ui/views/notifications/notification-permission#new-apps
代码:这是处理程序

  1. val pushNotificationPermissionLauncher = registerForActivityResult(ActivityResultContracts.RequestPermission()) { granted ->
  2. //handle code after permission granted
  3. }

这是权限的启动程序:

  1. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
  2. pushNotificationPermissionLauncher.launch(android.Manifest.permission.POST_NOTIFICATIONS)
  3. }

相关问题