Android 14 ForegroundServiceStartNotAllowedException: Service.startForeground() 不允许
创始人
2024-08-12 20:00:52
0

在 Android 8.0(API级别26)及更高版本中,出于性能和安全原因,应用不再允许在后台启动前台服务。如果你尝试在后台启动前台服务,将会抛出 ForegroundServiceStartNotAllowedException。

要解决这个问题,你可以使用以下两种方法之一:

  1. 将服务调整为后台服务:如果你的服务不需要在前台显示通知,可以将其更改为后台服务。后台服务在 Android 8.0 及更高版本中仍然可用。将服务从 startForeground() 方法更改为 startService() 方法即可。
// 启动服务
startService(new Intent(context, YourService.class));
  1. 将服务与通知结合使用:如果你的服务需要在前台显示通知,你需要使用 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 的两种常见方法。根据你的需求选择适合的方法即可。

相关内容

热门资讯

安装apache-beam==... 出现此错误可能是因为用户的Python版本太低,而apache-beam==2.34.0需要更高的P...
避免在粘贴双引号时向VS 20... 在粘贴双引号时向VS 2022添加反斜杠的问题通常是由于编辑器的自动转义功能引起的。为了避免这个问题...
Android Recycle... 要在Android RecyclerView中实现滑动卡片效果,可以按照以下步骤进行操作:首先,在项...
omi系统和安卓系统哪个好,揭... OMI系统和安卓系统哪个好?这个问题就像是在问“苹果和橘子哪个更甜”,每个人都有自己的答案。今天,我...
原生ios和安卓系统,原生对比... 亲爱的读者们,你是否曾好奇过,为什么你的iPhone和安卓手机在操作体验上有着天壤之别?今天,就让我...
Android - 无法确定任... 这个错误通常发生在Android项目中,表示编译Debug版本的Java代码时出现了依赖关系问题。下...
Android - NDK 预... 在Android NDK的构建过程中,LOCAL_SRC_FILES只能包含一个项目。如果需要在ND...
Akka生成Actor问题 在Akka框架中,可以使用ActorSystem对象生成Actor。但是,当我们在Actor类中尝试...
Agora-RTC-React... 出现这个错误原因是因为在 React 组件中使用,import AgoraRTC from “ago...
安装了Anaconda之后找不... 在安装Anaconda后,如果找不到Jupyter Notebook,可以尝试以下解决方法:检查环境...