在 Android 8.0(API级别26)及更高版本中,出于性能和安全原因,应用不再允许在后台启动前台服务。如果你尝试在后台启动前台服务,将会抛出 ForegroundServiceStartNotAllowedException。
要解决这个问题,你可以使用以下两种方法之一:
startForeground()
方法更改为 startService()
方法即可。// 启动服务
startService(new Intent(context, YourService.class));
startForegroundService()
方法启动服务,并在服务启动后调用 startForeground()
方法设置前台通知。// 启动前台服务
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
context.startForegroundService(new Intent(context, YourService.class));
} else {
context.startService(new Intent(context, YourService.class));
}
// 在服务中设置前台通知
public class YourService extends Service {
private static final int NOTIFICATION_ID = 1;
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// 设置前台通知
Notification notification = buildNotification();
startForeground(NOTIFICATION_ID, notification);
// 执行服务逻辑
// ...
return START_STICKY;
}
private Notification buildNotification() {
// 构建通知
// ...
}
}
请注意,如果你使用了第二种方法,你还需要在 AndroidManifest.xml 文件中为服务添加相应的前台服务声明:
以上是解决 Android 14 ForegroundServiceStartNotAllowedException 的两种常见方法。根据你的需求选择适合的方法即可。