-
Notifications
You must be signed in to change notification settings - Fork 80
/
LocationUpdateService.kt
222 lines (190 loc) · 8.1 KB
/
LocationUpdateService.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
/*
* Copyright (c) 2016 Marien Raat <marienraat@riseup.net>
* Copyright (c) 2017 Stephen Michel <s@smichel.me>
* SPDX-License-Identifier: GPL-3.0-or-later
*
* This file incorporates work covered by the following copyright and
* permission notice:
*
* Copyright (c) 2015 Chris Nguyen
*
* Permission to use, copy, modify, and/or distribute this software
* for any purpose with or without fee is hereby granted, provided
* that the above copyright notice and this permission notice appear
* in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL
* WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE
* AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR
* CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
* OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
* NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
* CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
package com.jmstudios.redmoon.service
import android.app.Service
import android.content.Context
import android.content.Intent
import android.location.Location
import android.location.LocationListener
import android.location.LocationManager
import android.os.Bundle
import android.os.IBinder
import com.jmstudios.redmoon.appContext
import com.jmstudios.redmoon.helper.Logger
import com.jmstudios.redmoon.helper.Permission
import com.jmstudios.redmoon.locationAccessDenied
import com.jmstudios.redmoon.locationService
import com.jmstudios.redmoon.Config
import org.greenrobot.eventbus.EventBus
import java.util.concurrent.TimeUnit
/**
* When the service starts, we request location updates. When we get a new
* location fix, we shut down the service. When we shut down (for any reason),
* we update the location with the last known location. This way, even if we
* didn't get a fix before the service was stopped, we might be able to get
* something more recent than the last time red moon updated location.
*/
class LocationUpdateService: Service(), LocationListener {
private inner class Provider(val provider: String) {
private var mRequested = false
val exists: Boolean
get() = locationManager.allProviders.contains(provider)
private val enabled: Boolean
get() = locationManager.isProviderEnabled(provider)
val searching: Boolean
get() = mRequested && enabled
val lastKnownLocation: Location?
get() = try {
locationManager.getLastKnownLocation(provider)
} catch (e: SecurityException) {
Log.i("Location permission not granted; Could not get last known location")
null
}
fun requestUpdates(listener: LocationListener) = when {
!exists -> {
Log.i("$provider doesn't exist; can't request updates")
postStatus(searching = false)
} mRequested -> {
Log.i("Already searching for updates using $provider")
postStatus(searching = enabled)
} else -> {
Log.i("Requesting location updates using $provider")
mRequested = true
if (enabled) { postStatus(searching = true) }
// If disabled, onProviderDisabled is called immediately
try {
locationManager.requestLocationUpdates(provider, 0, 0f, listener)
} catch(e: SecurityException) {
Log.i("Location permission not granted; cannot update location.")
}
}
}
}
// Starts null so we don't send duplicate status messages on init
private var mIsForeground: Boolean? = null
// Convenience to avoid null checks
private val isForeground
get() = mIsForeground ?: false
private var mNetworkProvider = Provider(LocationManager.NETWORK_PROVIDER)
private var mGpsProvider = Provider(LocationManager.GPS_PROVIDER)
private var mIsSearching: Boolean? = null
private val locationManager: LocationManager
get() = appContext.getSystemService(Context.LOCATION_SERVICE) as LocationManager
private val lastKnownLocation: Location?
get() = mGpsProvider.lastKnownLocation ?: mNetworkProvider.lastKnownLocation
private val locationUpToDate: Boolean
get() = lastKnownLocation?.time?.isRecent ?: Config.location.third?.isRecent ?: false
private val Long.isRecent: Boolean
get() = 1 > TimeUnit.MILLISECONDS.toHours(System.currentTimeMillis() - this)
override fun onCreate() {
super.onCreate()
Log.i("onCreate")
when {
locationUpToDate -> {
Log.i("Last known location is recent enough.")
stopSelf()
} mNetworkProvider.exists -> {
mNetworkProvider.requestUpdates(this)
} mGpsProvider.exists -> {
mGpsProvider.requestUpdates(this)
} else -> {
Log.i("No good providers, only: ${locationManager.allProviders}")
stopSelf()
}
}
}
override fun onStartCommand(intent: Intent, flags: Int, startId: Int): Int {
Log.i("onStartCommand($intent, $flags, $startId)")
if (mIsForeground != null) {
val searching = mNetworkProvider.searching || mGpsProvider.searching
EventBus.getDefault().post(locationService(searching))
}
val fg = intent.getBooleanExtra(BUNDLE_KEY_FOREGROUND, false)
mIsForeground = fg || isForeground
// Do not attempt to restart if the hosting process is killed by Android
return Service.START_NOT_STICKY
}
// Prevent binding.
override fun onBind(intent: Intent): IBinder? {
return null
}
override fun onLocationChanged(location: Location) {
Log.i("Location search succeeded")
stopSelf()
}
override fun onStatusChanged(provider: String, status: Int, extras: Bundle) {
Log.i("Provider $provider changed to status $status with extras $extras")
}
override fun onProviderEnabled(provider: String) {
Log.i("onProviderEnabled: $provider")
postStatus(searching = true)
}
override fun onProviderDisabled(provider: String) {
Log.i("onProviderDisabled: $provider")
if (!isForeground) {
Log.i("Avoiding gps for background updates")
stopSelf()
} else when (provider) {
mNetworkProvider.provider -> mGpsProvider.requestUpdates(this)
mGpsProvider.provider -> mNetworkProvider.requestUpdates(this)
else -> Log.w("We shouldn't be getting $provider updates")
}
}
override fun onDestroy() {
Log.i("onDestroy")
if (Permission.Location.isGranted) {
locationManager.removeUpdates(this)
lastKnownLocation?.apply {
Config.location = Triple(latitude.toString(), longitude.toString(), time)
}
}
super.onDestroy()
EventBus.getDefault().post(locationService(false, isRunning = false))
}
// Filters duplicates
private fun postStatus(searching: Boolean) {
if (mIsSearching != searching) {
Log.i("posting: $searching")
mIsSearching = searching
EventBus.getDefault().post(locationService(searching))
}
}
companion object : Logger() {
private const val BUNDLE_KEY_FOREGROUND = "jmstudios.bundle.key.FOREGROUND"
private val intent: Intent
get() = Intent(appContext, LocationUpdateService::class.java)
fun update(foreground: Boolean = true) {
Log.i("Received request")
if (!Permission.Location.isGranted) {
EventBus.getDefault().post(locationAccessDenied())
} else if (Config.scheduleOn && Config.useLocation) {
val i = intent.putExtra(BUNDLE_KEY_FOREGROUND, foreground)
appContext.startService(i)
} else {
appContext.stopService(intent)
}
}
}
}