引导完成后如何在 Oreo 中启动前台服务?

How to start a Foreground Service in Oreo and up after boot complete?

我正在开发一个应用程序,我想在其中启动前台服务在启动完成后。我知道我无法在广播中开始服务,这就是我问这个问题的原因。我没有找到任何有用的细节来继续前进。我正在使用前台服务,它每分钟都会为我提供位置更新。

为了启动监听,我使用的是 Broadcast-Receiver。

AndroidManifest.xml我写了这个

<receiver
     android:name=".services.receiver.StartUpdateReceiver"
     android:enabled="true"
     android:exported="true"
     android:permission="android.permission.RECEIVE_BOOT_COMPLETED">
     <intent-filter android:priority="1000">
         <action android:name="android.intent.action.BOOT_COMPLETED" />
     </intent-filter>
</receiver>

并且在收到启动接收器后,我想启动相同的前台服务以在每分钟后获取位置更新。当我单击 activity 中的按钮启动前台服务以获取位置更新时,效果很好。

请告诉我如何实现这个目标?

使用startForegroundService()启动前台服务。

Android 8.0 introduces the new method startForegroundService() to start a new service in the foreground. After the system has created the service, the app has five seconds to call the service's startForeground() method to show the new service's user-visible notification. If the app does not call startForeground() within the time limit, the system stops the service and declares the app to be ANR. As mentioned in Developers Site Check this