簡體   English   中英

Android Kotlin 前台服務在一段時間后停止

[英]Android Kotlin Foreground Service stops after some time

我正在開發用於用戶跟蹤的前台位置服務。 每次位置更新時,此服務都會向 API 發送請求以更新當前 position。 問題是當應用程序被置於后台或屏幕被鎖定時,服務會在一段時間后停止發送請求(通常大約 1 分鍾,在此期間發送大約 10 個請求)。 應用程序恢復后,服務再次開始工作,並且在最小化/鎖定屏幕后重復該場景。

onStartCommand ,我嘗試返回多個啟動選項,但都沒有奏效。 我已經在 Android 10 和 11 上測試了該應用程序。

服務源代碼:

class LocationService: Service()  {

    @Inject
    lateinit var apiService: ApiService

    private val composite = CompositeDisposable()

    private var locationManager: LocationManager? = null
    private var locationListener: LocationListener? = null

    override fun onBind(p0: Intent?): IBinder? =
        null

    val NOTIFICATION_CHANNEL_ID = "location_tracking"
    val NOTIFICATION_CHANNEL_NAME = "Location tracking"
    val NOTIFICATION_ID = 101

    var isFirstRun = true

    @SuppressLint("MissingPermission")
    override fun onCreate() {
        App.component.inject(this)

        setupLocationListener()

        locationManager = getSystemService(LOCATION_SERVICE) as LocationManager?
        val criteria = Criteria()
        criteria.accuracy = Criteria.ACCURACY_FINE
        val provider = locationManager?.getBestProvider(criteria, true)

        val minTime = 5*1000L
        if(provider != null) locationManager?.requestLocationUpdates(provider, minTime, 0f, locationListener)

        super.onCreate()
    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        if (isFirstRun) {
            startForegroundService()
            isFirstRun = false
        } else {
            Timber.d {"Resuming service"}
        }

        return super.onStartCommand(intent, flags, startId)
    }

    private fun startForegroundService() {
        val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager

        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) createNotificationChannel(notificationManager)

        val notificationBuilder = NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID)
                .setAutoCancel(false)
                .setOngoing(true)
                .setSmallIcon(R.drawable.ic_notification)
                .setContentTitle(NOTIFICATION_CHANNEL_NAME)
                .setContentIntent(getMainActivityIntent())

        startForeground(NOTIFICATION_ID, notificationBuilder.build())
    }

    private fun getMainActivityIntent()
        = PendingIntent.getActivity(this, 0, Intent(this, MainActivity::class.java)
            .also { it.action = R.id.action_global_navigationScreenFragment.toString() }, FLAG_UPDATE_CURRENT)

    @RequiresApi(Build.VERSION_CODES.O)
    private fun createNotificationChannel(notificationManager: NotificationManager) {
        val channel = NotificationChannel(NOTIFICATION_CHANNEL_ID, NOTIFICATION_CHANNEL_NAME, IMPORTANCE_LOW)
        notificationManager.createNotificationChannel(channel)
    }

    private fun setupLocationListener() {
        locationListener = object: LocationListener {

            override fun onLocationChanged(location: Location) {
                val cords = GeoCoordinatesDTO(location.latitude.toFloat(), location.longitude.toFloat())
                try {
                    composite.add(apiService.mobileUserAccountReportPosition(cords)
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(
                            {},
                            { t ->
                                if(t is RuntimeException) {
                                    e(t)
                                }
                            }
                        ))
                } catch(e: Exception) {
                    Log.e("GPS", "error: $e")
                }
            }

            override fun onStatusChanged(provider: String, status: Int, extras: Bundle) {}

            override fun onProviderEnabled(provider: String) {}

            override fun onProviderDisabled(provider: String) {}

        }
    }

    override fun onDestroy() {
        try {
            locationManager?.removeUpdates(locationListener)
        } catch(e: DeadObjectException) {}
        super.onDestroy()
    }

}

該服務從MainActivity中的onStart函數啟動

private fun initializeLocationMonitor() {
    locationService = Intent(this, LocationService::class.java)
    if(!this.isServiceRunning(LocationService::class.java)) {
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
            startForegroundService(locationService)
        } else {
            startService(locationService)
        }
        sendBroadcast(locationService)
    }
}

我在清單中具有以下權限並注冊了服務:

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />

<service
    android:name=".Services.LocationService"
    android:enabled="true"
    android:exported="true"
    tools:ignore="ExportedService,InnerclassSeparator"
    android:foregroundServiceType="location"/>
  1. 保持設備喚醒 - https://developer.android.com/training/scheduling/wakelock
// global service variable
private var wakeLock: PowerManager.WakeLock? = null
...
// initialize before setupLocationListener() is called
wakeLock =
            (getSystemService(Context.POWER_SERVICE) as PowerManager).run {
                newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "LocationService::lock").apply {
                    acquire(10*1000L)  // 10 seconds
                }
            }

顯現:

<uses-permission android:name="android.permission.WAKE_LOCK" />
  1. 檢查您的應用程序是否在應用程序設置中限制了數據使用和電池服務器。

如果您的最小 sdk 為 14+,則最好使用 WorkManager。 它將使您免於使用和管理前台服務的許多麻煩。

https://developer.android.com/topic/libraries/architecture/workmanager

發送位置更新是 WorkManager 的最佳用例之一。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM