使用以下代码,我正在尝试从Broadcast receiver
启动新服务,但是服务似乎没有启动。在kotlin中启动一个服务的正确方法是什么?
val intent = Intent(context, LocationService::class.java)
if (context != null) {
context.startService(intent)
}
使用以下代码,我正在尝试从Broadcast receiver
启动新服务,但是服务似乎没有启动。在kotlin中启动一个服务的正确方法是什么?
val intent = Intent(context, LocationService::class.java)
if (context != null) {
context.startService(intent)
}
试一试
val intent = Intent(context, LocationService::class.java)
if (context != null) {
context.startService(intent)
}
别忘记在 manifest
文件中注册你的 service
<service android:name="packageName.LocationService"/>
在 Kotlin 中使用安全访问压缩:
val intent = Intent(context, LocationService::class.java)
context?.startService(intent)
同时在您的清单中定义您的服务。
<manifest ...>
<application ...>
<service
android:name="package.LocationService">
</service>
</application>
</manifest>
<service android:name=".LocationService"/>
。
startService
返回非空值,这将表明服务已经启动。请注意,在Android O中,startService
已被弃用,并且对于targetSdk 26
会抛出异常。 - Miha_x64