我正在尝试遵循新的Android O准则来启动位置更新的前台服务 . 当我调用 context.startForegroundService(foregroundIntent)
在服务类中没有任何反应时,甚至不会调用 onCreate()
. 但是,应用程序继续运行没有任何错误 .
这是我的意图:
val foregroundIntent = Intent(context, GeofenceForegroundService::class.java)
我用来创建Intent的上下文是一个活动上下文,而不是应用程序上下文 .
以下是Android Manifest中的服务:
<application
...
<service android:name=".services.GeofenceForegroundService"
android:exported="false" />
</application>
这是onCreate,onStartCommand和服务类中未启动的onBind .
override fun onCreate() {
super.onCreate()
fusedLocationClient = LocationServices.getFusedLocationProviderClient(this) //Break point here
locationRequest.interval = UPDATE_INTERVAL_IN_MILLISECONDS
locationRequest.fastestInterval =
FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS
locationRequest.priority = LocationRequest.PRIORITY_HIGH_ACCURACY
// setup notification channel if Android O or higher
}
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
val DONT_SET_EXPIRE: Long = -123456
val expirationTime = intent?.getLongExtra(REQUEST_EXPIRATION_EXTRA, DONT_SET_EXPIRE)
eventName = intent?.getStringExtra(EVENT_NAME_EXTRA)
if(expirationTime != null && expirationTime != DONT_SET_EXPIRE) {
locationRequest.expirationTime = expirationTime
}
// If the location permission is off stop the service, it isn't doing anyone any good.
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
startForeground(NOTIFICATION_ID, makeNotification())
fusedLocationClient.requestLocationUpdates(locationRequest, locationCallback, null)
} else {
stopSelf()
}
return START_STICKY
}
override fun onBind(p0: Intent?): IBinder? = null
我试过调用 context.startService(foregroundService)
而且似乎没有任何变化 . 当应用程序位于前台时,始终会调用此代码,因此背景限制不应成为问题 .
我们非常感谢您提供的任何帮助,如果您有任何其他代码需要查看以便找到任何问题,请告诉我 . 这是我第一次使用前台服务,所以如果我犯了一个非常明显的错误,请耐心等待 . 我试图彻底阅读如何正确地做事,但有可能我错过了应该直截了当的事情 .