作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有一项服务,它会不时更新我的后端,使用用户的最新位置,问题是,一些用户报告前台通知有时会消失,但并非所有用户都发生这种情况,可能成为每天使用该应用程序 8 小时的用户,它不会消失,但 Crashlytics 上不会出现崩溃。
这是我的服务类
package com.xxxxxxx.xxxxxxxx.service
import android.annotation.SuppressLint
import android.app.Notification
import android.app.Notification.FLAG_NO_CLEAR
import android.app.Notification.FLAG_ONGOING_EVENT
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.app.PendingIntent.FLAG_UPDATE_CURRENT
import android.app.Service
import android.content.Intent
import android.content.Intent.FLAG_ACTIVITY_CLEAR_TOP
import android.content.Intent.FLAG_ACTIVITY_SINGLE_TOP
import android.graphics.Color
import android.location.Location
import android.os.Build.VERSION.SDK_INT
import android.os.Build.VERSION_CODES.O
import android.os.IBinder
import android.util.Base64
import android.util.Base64.DEFAULT
import androidx.annotation.RequiresApi
import androidx.core.app.NotificationCompat
import androidx.core.content.ContextCompat
import com.google.android.gms.location.LocationCallback
import com.google.android.gms.location.LocationRequest
import com.google.android.gms.location.LocationResult
import com.google.android.gms.location.LocationServices
import com.google.android.gms.maps.model.LatLng
import com.xxxx.commons.XXXXXXCommons
import com.xxxxxxx.xxxxxxxx.R
import com.xxxxxxx.xxxxxxxx.di.DataSourceModule
import com.xxxxxxx.xxxxxxxx.domain.GetAppStateUseCase.Companion.LOCATION_DELIMITER
import com.xxxxxxx.xxxxxxxx.model.local.CachedLocation
import com.xxxxxxx.xxxxxxxx.model.local.DriverLocation
import com.xxxxxxx.xxxxxxxx.utils.LOCATION_PERMISSIONS
import com.xxxxxxx.xxxxxxxx.utils.OnGoingTrip
import com.xxxxxxx.xxxxxxxx.utils.checkPermissions
import com.xxxxxxx.xxxxxxxx.view.activity.SplashActivity
import kotlinx.coroutines.CoroutineExceptionHandler
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.cancel
import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch
import kotlin.text.Charsets.UTF_8
class LocationTrackingService : Service() {
private companion object {
const val NOTIFICATION_ID = 856
const val FOREGROUND_SERVICE_ID = 529
const val LOCATION_UPDATE_INTERVAL = 10000L
const val LOCATION_UPDATE_FASTEST_INTERVAL = 5000L
}
private val updateJob: Job = Job()
private val errorHandler = CoroutineExceptionHandler { _, throwable ->
XXXXXXCommons.crashHandler?.log(throwable)
}
private val locationTrackingCoroutineScope =
CoroutineScope(Dispatchers.IO + updateJob + errorHandler)
private val rideApiService by lazy { DataSourceModule.provideRideApiService() }
private val locationDao by lazy { DataSourceModule.provideLocationDao(XXXXXXCommons.provideApplicationContext()) }
private val locationRequest = LocationRequest().apply {
interval = LOCATION_UPDATE_INTERVAL
fastestInterval = LOCATION_UPDATE_FASTEST_INTERVAL
priority = LocationRequest.PRIORITY_HIGH_ACCURACY
}
private val callback = object : LocationCallback() {
override fun onLocationResult(result: LocationResult?) = onLocationReceived(result)
}
@SuppressLint("MissingPermission")
private fun requestLocationUpdates() {
if (checkPermissions(*LOCATION_PERMISSIONS)) {
LocationServices.getFusedLocationProviderClient(this)
.requestLocationUpdates(locationRequest, callback, null)
}
}
private fun onLocationReceived(result: LocationResult?) = result?.lastLocation?.run {
postDriverLocation(this)
} ?: Unit
private fun postDriverLocation(location: Location) {
val driverLocation = DriverLocation(
location.latitude.toFloat(),
location.longitude.toFloat(),
location.bearing,
OnGoingTrip.rideData.rideId,
OnGoingTrip.orderData.orderId
)
OnGoingTrip.currentLocation = LatLng(location.latitude, location.longitude)
OnGoingTrip.reportLocationUpdate()
locationTrackingCoroutineScope.launch(Dispatchers.IO) {
cacheDriverLocation(driverLocation)
rideApiService.postCurrentDriverLocation(driverLocation)
}
}
private suspend fun cacheDriverLocation(driverLocation: DriverLocation) {
val bytes = "${driverLocation.latitude}$LOCATION_DELIMITER${driverLocation.longitude}"
.toByteArray(UTF_8)
val safeLocation = Base64.encode(bytes, DEFAULT).toString(UTF_8)
locationDao.createOrUpdate(CachedLocation(location = safeLocation))
}
override fun onBind(intent: Intent): IBinder? = null
override fun onCreate() {
super.onCreate()
buildNotification(
if (SDK_INT >= O) {
createNotificationChannel(getString(R.string.app_name))
} else {
NOTIFICATION_ID.toString()
}
)
requestLocationUpdates()
}
override fun onDestroy() {
super.onDestroy()
if (locationTrackingCoroutineScope.isActive) {
locationTrackingCoroutineScope.cancel()
}
LocationServices.getFusedLocationProviderClient(this).removeLocationUpdates(callback)
(getSystemService(NOTIFICATION_SERVICE) as? NotificationManager)?.cancel(NOTIFICATION_ID)
}
@RequiresApi(O)
private fun createNotificationChannel(channelName: String): String {
val chan = NotificationChannel(
NOTIFICATION_ID.toString(),
channelName,
NotificationManager.IMPORTANCE_NONE
)
chan.lightColor = Color.CYAN
chan.lockscreenVisibility = Notification.VISIBILITY_PRIVATE
val service = getSystemService(NOTIFICATION_SERVICE) as NotificationManager
service.createNotificationChannel(chan)
return NOTIFICATION_ID.toString()
}
private fun buildNotification(channelId: String) {
val ctx = this
(getSystemService(NOTIFICATION_SERVICE) as? NotificationManager)?.run {
val intent = Intent(ctx, SplashActivity::class.java).apply {
flags = FLAG_ACTIVITY_CLEAR_TOP or FLAG_ACTIVITY_SINGLE_TOP
}
val resultPendingIntent =
PendingIntent.getActivity(ctx, 0, intent, FLAG_UPDATE_CURRENT)
val notification = NotificationCompat.Builder(ctx, channelId)
.setSmallIcon(R.drawable.ic_xxxxxx_icon_background)
.setColor(ContextCompat.getColor(ctx, R.color.xxxxxxTurquoise))
.setContentTitle(ctx.getString(R.string.app_name))
.setOngoing(true)
.setContentText(ctx.getString(R.string.usage_message))
.setContentIntent(resultPendingIntent)
.build().apply { flags = FLAG_ONGOING_EVENT or FLAG_NO_CLEAR }
startForeground(FOREGROUND_SERVICE_ID, notification)
}
}
}
这是我启动服务的方式:
startService(Intent(this, LocationTrackingService::class.java));
以下是我拥有的权限以及我在 AndroidManifest.xml 上声明它的方式:
<service
android:name=".service.LocationTrackingService"
android:enabled="true"
android:exported="true" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION" />
编辑
最佳答案
Android 11 有几个最新的限制。很难提供一个准确的解决方案。以下是您应该重新检查的几件事,可能会解决您的问题:
关于java - 前台服务被杀,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66728240/
我试图理解什么是 -XX:OnOutOfMemoryError='kill %p' 下面的命令是什么意思? 我不确定 %p 是什么意思? exec /bin/bash -c "LD_LIBRARY_P
我试图理解什么是 -XX:OnOutOfMemoryError='kill %p' 下面的命令是什么意思? 我不确定 %p 是什么意思? exec /bin/bash -c "LD_LIBRARY_P
这个问题在这里已经有了答案: Solving "adb server version doesn't match this client" error [duplicate] (17 个答案) 关闭
我是一名优秀的程序员,十分优秀!