java - 前台服务被杀

标签 java android kotlin service android-service

我有一项服务,它会不时更新我的​​后端,使用用户的最新位置,问题是,一些用户报告前台通知有时会消失,但并非所有用户都发生这种情况,可能成为每天使用该应用程序 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 9 和 10,少数从 5 到 8,几乎没有 11
我很乐意分享更多信息。

最佳答案

Android 11 有几个最新的限制。很难提供一个准确的解决方案。以下是您应该重新检查的几件事,可能会解决您的问题:

  • 禁用 电池优化用于设备中的应用程序。
  • 检查设备是否未在 中运行打盹模式 .
  • 指定 安卓:前台服务类型在 list 中。
  • 关于java - 前台服务被杀,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66728240/

    相关文章:

    android - 如何实现Android TvView

    kotlin - 检查字符是否表示Kotlin中的非字符代码点

    Android导航 - 弹出返回堆栈时删除操作栏后退按钮

    java - Tapestry 5.3.8 提交包含区域的表单

    java - 字符串操作,从同一行提取某些值

    android - Ios 版本的应用程序可以运行,但由于没有找到适合 React Native App 的 AccessToken 的构造函数,Android 版本失败

    android - 如何圆角 ListView 顶部和底部的列表项? (不仅适用于顶部和底部项目)

    kotlin - 如何定义我作为参数传递的函数作为可空值?

    使用多线程的 Java Rest 客户端

    java - 阻止 Android 通知栏出现在触摸事件上