Android служба отслеживания - PullRequest
0 голосов
/ 23 апреля 2020

Я работаю в компании по доставке, и они хотят отслеживать своих сотрудников в течение их 8-часовой смены. Я использую ядро ​​asp. net с Azure SignalR для отправки информации, и пользователь подключается, как только приложение запускается, но затем внезапно отслеживание останавливается, а иногда и не восстанавливается. Будем благодарны за любую помощь или совет.

Вот услуга, которую я использую:

class TrackingService : Service() {

private val notificationId = 298536
private lateinit var locationManager: LocationManager
private lateinit var fusedLocationProviderClient: FusedLocationProviderClient
private lateinit var bearerToken: String

private val locationRequest: LocationRequest = LocationRequest()
        .setFastestInterval(10*1000)
        .setInterval(15*1000)
        .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
        .setExpirationDuration(Long.MAX_VALUE)

private lateinit var locationCallback: LocationCallback
private lateinit var locationConnectionHub: HubConnection

private var started = false

override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
    Log.v("LocationTracker", "onStartCommand method called")
    if (intent != null) {
        bearerToken = intent.getStringExtra("token")
    }

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

override fun onCreate() {
    super.onCreate()
    Log.v("LocationTracker", "onCreate method called")
    locationManager = getSystemService(Context.LOCATION_SERVICE) as LocationManager
    fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this)
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        val notification: Notification = Notification.Builder(this, "biggie_tracker")
                .setContentTitle("Biggie Delivery")
                .setContentText("Recibiendo pedidos")
                // .setSmallIcon(R.drawable.o)
                // .setLargeIcon(aBitmap)
                .build()
        startForeground(notificationId, notification)
    }

    locationConnectionHub = HubConnectionBuilder
            .create("https://biggie-locations.azurewebsites.net/hubs/tracking")
            .withAccessTokenProvider(Single.defer { Single.just(bearerToken) })
            .withTransport(TransportEnum.WEBSOCKETS)
            .shouldSkipNegotiate(false)
            .withHandshakeResponseTimeout(5000)
            .build()

    locationCallback = DeliveryLocationCallback(locationConnectionHub)
}

override fun onDestroy() {
    Log.v("LocationTracker", "onDestroy method called")
    super.onDestroy()
    stopLocationUpdates()
    locationConnectionHub.stop().subscribe({
        Log.v("LocationTracker", "OnDestroy locationHub stop finished ${locationConnectionHub.connectionState}")
    }, {
        Log.e("LocationTracker", "ERROR! on OnDestroy locationHub stop ${locationConnectionHub.connectionState}", it)
    })
}

override fun onBind(intent: Intent?): IBinder? {
    return null
}

private fun startLocationUpdates() {
    if (started) return
    Log.v("LocationTracker", "startLocationUpdates method called")
    locationConnectionHub.start().subscribe({
        Log.v("LocationTracker", "startLocationUpdates locationHub start finished ${locationConnectionHub.connectionState}")
    }, {
        Log.e("LocationTracker", "ERROR! on startLocationUpdates locationHub start ${locationConnectionHub.connectionState}", it)
    })
    fusedLocationProviderClient.requestLocationUpdates(locationRequest, locationCallback, Looper.myLooper())
    started = true
}

private fun stopLocationUpdates() {
    Log.v("LocationTracker", "stopLocationUpdates method called")
    if (!started) return
    fusedLocationProviderClient.removeLocationUpdates(locationCallback)
    started = false
}}

Вот обратный звонок:

class DeliveryLocationCallback(private val locationHub: HubConnection) : LocationCallback() {

private var locationAvailable = true

override fun onLocationResult(locationResult: LocationResult?) {
    super.onLocationResult(locationResult)
    if (locationHub.connectionState == HubConnectionState.DISCONNECTED) {
        locationHub.start().subscribe({
            Log.v("LocationTracker", "startLocationUpdates locationHub start finished ${locationHub.connectionState}")
        }, {
            Log.e("LocationTracker", "ERROR! on startLocationUpdates locationHub start ${locationHub.connectionState}")
        })
        return
    }
    val model = TrackModel(
            PointModel(
                    locationResult?.lastLocation?.latitude,
                    locationResult?.lastLocation?.longitude
            )
    )
    try {
        locationHub.send("Track", model)
        Log.v("LocationTracker", "Sending location ${locationResult?.lastLocation?.latitude}, ${locationResult?.lastLocation?.longitude}")
    } catch (e: Exception) {
        Log.v("LocationTracker", "Socket is disconnected!")
    }
}

override fun onLocationAvailability(availability: LocationAvailability?) {
    super.onLocationAvailability(availability)
    locationAvailable = availability?.isLocationAvailable!!
    Log.v("LocationTracker", "Location Availability: $locationAvailable")
}}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...