-
Notifications
You must be signed in to change notification settings - Fork 318
/
MapboxNavigation.kt
744 lines (684 loc) · 31.2 KB
/
MapboxNavigation.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
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
package com.mapbox.navigation.core
import android.Manifest.permission.ACCESS_COARSE_LOCATION
import android.Manifest.permission.ACCESS_FINE_LOCATION
import android.content.Context
import android.hardware.SensorEvent
import androidx.annotation.RequiresPermission
import com.mapbox.android.core.location.LocationEngine
import com.mapbox.annotation.module.MapboxModuleType
import com.mapbox.api.directions.v5.models.DirectionsRoute
import com.mapbox.api.directions.v5.models.RouteOptions
import com.mapbox.base.common.logger.Logger
import com.mapbox.base.common.logger.model.Message
import com.mapbox.base.common.logger.model.Tag
import com.mapbox.common.module.provider.MapboxModuleProvider
import com.mapbox.navigation.base.internal.VoiceUnit
import com.mapbox.navigation.base.internal.accounts.SkuTokenProvider
import com.mapbox.navigation.base.internal.accounts.UrlSkuTokenProvider
import com.mapbox.navigation.base.options.NavigationOptions
import com.mapbox.navigation.base.options.OnboardRouterOptions
import com.mapbox.navigation.base.route.Router
import com.mapbox.navigation.base.trip.model.RouteProgress
import com.mapbox.navigation.base.trip.notification.NotificationAction
import com.mapbox.navigation.base.trip.notification.TripNotification
import com.mapbox.navigation.core.MapboxNavigation.Companion.defaultNavigationOptionsBuilder
import com.mapbox.navigation.core.accounts.NavigationAccountsSession
import com.mapbox.navigation.core.arrival.ArrivalController
import com.mapbox.navigation.core.arrival.ArrivalObserver
import com.mapbox.navigation.core.arrival.ArrivalProgressObserver
import com.mapbox.navigation.core.arrival.AutoArrivalController
import com.mapbox.navigation.core.directions.session.DirectionsSession
import com.mapbox.navigation.core.directions.session.RoutesObserver
import com.mapbox.navigation.core.directions.session.RoutesRequestCallback
import com.mapbox.navigation.core.fasterroute.FasterRouteController
import com.mapbox.navigation.core.fasterroute.FasterRouteDetector
import com.mapbox.navigation.core.fasterroute.FasterRouteObserver
import com.mapbox.navigation.core.fasterroute.RouteComparator
import com.mapbox.navigation.core.internal.MapboxDistanceFormatter
import com.mapbox.navigation.core.internal.accounts.MapboxNavigationAccounts
import com.mapbox.navigation.core.internal.trip.service.TripService
import com.mapbox.navigation.core.reroute.MapboxRerouteController
import com.mapbox.navigation.core.reroute.RerouteController
import com.mapbox.navigation.core.reroute.RerouteState
import com.mapbox.navigation.core.routeoptions.MapboxRouteOptionsProvider
import com.mapbox.navigation.core.routerefresh.RouteRefreshController
import com.mapbox.navigation.core.telemetry.MapboxNavigationTelemetry
import com.mapbox.navigation.core.telemetry.events.FeedbackEvent
import com.mapbox.navigation.core.trip.session.BannerInstructionsObserver
import com.mapbox.navigation.core.trip.session.LocationObserver
import com.mapbox.navigation.core.trip.session.OffRouteObserver
import com.mapbox.navigation.core.trip.session.RouteProgressObserver
import com.mapbox.navigation.core.trip.session.TripSession
import com.mapbox.navigation.core.trip.session.TripSessionStateObserver
import com.mapbox.navigation.core.trip.session.VoiceInstructionsObserver
import com.mapbox.navigation.metrics.MapboxMetricsReporter
import com.mapbox.navigation.navigator.internal.MapboxNativeNavigator
import com.mapbox.navigation.navigator.internal.MapboxNativeNavigatorImpl
import com.mapbox.navigation.utils.internal.JobControl
import com.mapbox.navigation.utils.internal.NetworkStatusService
import com.mapbox.navigation.utils.internal.ThreadController
import com.mapbox.navigation.utils.internal.ifNonNull
import com.mapbox.navigation.utils.internal.monitorChannelWithException
import java.lang.reflect.Field
import kotlinx.coroutines.channels.ReceiveChannel
private const val MAPBOX_NAVIGATION_USER_AGENT_BASE = "mapbox-navigation-android"
private const val MAPBOX_NAVIGATION_UI_USER_AGENT_BASE = "mapbox-navigation-ui-android"
private const val MAPBOX_NAVIGATION_TOKEN_EXCEPTION_OFFBOARD_ROUTER =
"You need to provide an access token in NavigationOptions in order to use the default OffboardRouter. " +
"Also see MapboxNavigation#defaultNavigationOptionsBuilder"
private const val MAPBOX_NAVIGATION_TOKEN_EXCEPTION_ONBOARD_ROUTER =
"You need to provide an access token in NavigationOptions in order to use the default OnboardRouter. " +
"Also see MapboxNavigation#defaultNavigationOptionsBuilder"
private const val MAPBOX_NAVIGATION_TOKEN_EXCEPTION = "You need to provide an access token in NavigationOptions " +
"Also see MapboxNavigation#defaultNavigationOptionsBuilder"
/**
* ## Mapbox Navigation Core SDK
* An entry point for interacting with and customizing a navigation session.
*
* **Only one instance of this class should be used per application process.**
*
* The Navigation Core SDK artifact is composed out of multiple separate artifacts or modules.
* TODO insert modules documentation
*
* The [MapboxNavigation] implementation can enter into a couple of internal states:
* - `Idle`
* - `Free Drive`
* - `Active Guidance`
*
* The SDK starts of in an `Idle` state.
*
* ### Location
* Whenever the [startTripSession] is called, the SDK will enter the `Free Drive` state starting to request and propagate location updates via the [LocationObserver].
*
* This observer provides 2 location update values in mixed intervals - either the raw one received from the provided [LocationEngine]
* or the enhanced one map-matched internally using SDK's native capabilities.
*
* In `Free Drive` mode, the enhanced location is computed using nearby to user location's routing tiles that are continuously updating in the background.
* This can be configured using the [OnboardRouterOptions] in the [NavigationOptions].
*
* If the session is stopped, the SDK will stop listening for raw location updates and enter the `Idle` state.
*
* ### Routing
* A route can be requested with [requestRoutes]. If the request is successful and returns a non-empty list of routes in the [RoutesObserver],
* the first route at index 0 is going to be chosen as a primary one.
*
* If the SDK is in an `Idle` state, it stays in this same state even when a primary route is available.
*
* If the SDK is already in the `Free Drive` mode or entering it whenever a primary route is available,
* the SDK will enter the `Active Guidance` mode instead and propagate meaningful [RouteProgress].
* Additionally, the enhanced location's map-matching will be more precise and based on the primary route itself.
*
* If a new routes request is made, or the routes are manually cleared, the SDK automatically fall back to either `Idle` or `Free Drive` state.
*
* You can use [setRoutes] to provide new routes, clear current ones, or change the route at primary index 0.
* todo should we expose a "primaryRouteIndex" field instead of relying on the list's order?
*
* @param navigationOptions a set of [NavigationOptions] used to customize various features of the SDK.
* Use [defaultNavigationOptionsBuilder] to set default options
*/
class MapboxNavigation(
val navigationOptions: NavigationOptions
) {
private val accessToken: String? = navigationOptions.accessToken
private val mainJobController: JobControl = ThreadController.getMainScopeAndRootJob()
private val directionsSession: DirectionsSession
private val navigator: MapboxNativeNavigator
private val tripService: TripService
private val tripSession: TripSession
private val navigationSession: NavigationSession
private val navigationAccountsSession = NavigationAccountsSession(navigationOptions.applicationContext)
private val logger: Logger
private val internalRoutesObserver: RoutesObserver
private val internalOffRouteObserver: OffRouteObserver
private val fasterRouteController: FasterRouteController
private val routeRefreshController: RouteRefreshController
private val arrivalProgressObserver: ArrivalProgressObserver
private var notificationChannelField: Field? = null
private val MAPBOX_NAVIGATION_NOTIFICATION_PACKAGE_NAME =
"com.mapbox.navigation.trip.notification.internal.MapboxTripNotification"
private val MAPBOX_NOTIFICATION_ACTION_CHANNEL = "notificationActionButtonChannel"
/**
* Reroute controller, by default uses [MapboxRerouteController].
*/
private var rerouteController: RerouteController?
init {
ThreadController.init()
logger = MapboxModuleProvider.createModule(MapboxModuleType.CommonLogger, ::paramsProvider)
navigator = NavigationComponentProvider.createNativeNavigator(
navigationOptions.deviceProfile,
logger
)
navigationSession = NavigationComponentProvider.createNavigationSession()
directionsSession = NavigationComponentProvider.createDirectionsSession(
MapboxModuleProvider.createModule(MapboxModuleType.NavigationRouter, ::paramsProvider)
)
directionsSession.registerRoutesObserver(navigationSession)
val notification: TripNotification = MapboxModuleProvider
.createModule(MapboxModuleType.NavigationTripNotification, ::paramsProvider)
if (notification.javaClass.name == MAPBOX_NAVIGATION_NOTIFICATION_PACKAGE_NAME) {
notificationChannelField =
notification.javaClass.getDeclaredField(MAPBOX_NOTIFICATION_ACTION_CHANNEL).apply {
isAccessible = true
}
}
tripService = NavigationComponentProvider.createTripService(
navigationOptions.applicationContext,
notification,
logger
)
tripSession = NavigationComponentProvider.createTripSession(
tripService = tripService,
locationEngine = navigationOptions.locationEngine,
navigatorPredictionMillis = navigationOptions.navigatorPredictionMillis,
navigator = navigator,
logger = logger
)
tripSession.registerStateObserver(navigationSession)
navigationSession.registerNavigationSessionStateObserver(navigationAccountsSession)
ifNonNull(accessToken) { token ->
logger.d(
Tag(MapboxNavigationTelemetry.TAG),
Message("MapboxMetricsReporter.init from MapboxNavigation main")
)
MapboxMetricsReporter.init(
navigationOptions.applicationContext,
accessToken ?: throw RuntimeException(MAPBOX_NAVIGATION_TOKEN_EXCEPTION),
obtainUserAgent(navigationOptions.isFromNavigationUi)
)
MapboxMetricsReporter.toggleLogging(navigationOptions.isDebugLoggingEnabled)
MapboxNavigationTelemetry.initialize(
navigationOptions.applicationContext,
this,
MapboxMetricsReporter,
navigationOptions.locationEngine.javaClass.name,
ThreadController.getMainScopeAndRootJob(),
navigationOptions,
obtainUserAgent(navigationOptions.isFromNavigationUi)
)
}
val routeOptionsProvider = MapboxRouteOptionsProvider(logger)
fasterRouteController = FasterRouteController(
directionsSession,
tripSession,
routeOptionsProvider,
FasterRouteDetector(RouteComparator()),
logger
)
routeRefreshController = RouteRefreshController(directionsSession, tripSession, logger)
routeRefreshController.start()
arrivalProgressObserver = ArrivalProgressObserver(tripSession)
setArrivalController()
rerouteController = MapboxRerouteController(
directionsSession,
tripSession,
routeOptionsProvider,
ThreadController,
logger
)
internalRoutesObserver = createInternalRoutesObserver()
internalOffRouteObserver = createInternalOffRouteObserver()
tripSession.registerOffRouteObserver(internalOffRouteObserver)
directionsSession.registerRoutesObserver(internalRoutesObserver)
}
/**
* Starts listening for location updates and enters an `Active Guidance` state if there's a primary route available
* or a `Free Drive` state otherwise.
*
* @see [registerTripSessionStateObserver]
* @see [registerRouteProgressObserver]
*/
@RequiresPermission(anyOf = [ACCESS_COARSE_LOCATION, ACCESS_FINE_LOCATION])
fun startTripSession() {
tripSession.start()
notificationChannelField?.let {
monitorNotificationActionButton(it.get(null) as ReceiveChannel<NotificationAction>)
}
}
/**
* Stops listening for location updates and enters an `Idle` state.
*
* @see [registerTripSessionStateObserver]
*/
fun stopTripSession() {
tripSession.stop()
}
/**
* Return the current [TripSession]'s state.
* The state is [STARTED] when the session is active, running a foreground service and
* requesting and returning location updates.
* The state is [STOPPED] when the session is inactive.
*
* @return current [TripSessionState]
* @see [registerTripSessionStateObserver]
*/
fun getTripSessionState() = tripSession.getState()
/**
* Requests a route using the provided [Router] implementation.
* If the request succeeds and the SDK enters an `Active Guidance` state, meaningful [RouteProgress] updates will be available.
*
* Use [RoutesObserver] and [MapboxNavigation.registerRoutesObserver] to observe whenever the routes list reference managed by the SDK changes, regardless of a source.
*
* Use [MapboxNavigation.setRoutes] to supply a transformed list of routes, or a list from an external source, to be managed by the SDK.
*
* @param routeOptions params for the route request
* @param routesRequestCallback listener that gets notified when request state changes
* @see [registerRoutesObserver]
* @see [registerRouteProgressObserver]
*/
@JvmOverloads
fun requestRoutes(
routeOptions: RouteOptions,
routesRequestCallback: RoutesRequestCallback? = null
) {
rerouteController?.interrupt()
directionsSession.requestRoutes(routeOptions, routesRequestCallback)
}
/**
* Set a list of routes.
*
* If the list is empty, the SDK will exit the `Active Guidance` state.
*
* If the list is not empty, the route at index 0 is going to be treated as the primary route
* and used for route progress, off route events and map-matching calculations.
*
* Use [RoutesObserver] and [MapboxNavigation.registerRoutesObserver] to observe whenever the routes list reference managed by the SDK changes, regardless of a source.
*
* @param routes a list of [DirectionsRoute]s
*/
fun setRoutes(routes: List<DirectionsRoute>) {
rerouteController?.interrupt()
directionsSession.routes = routes
}
/**
* Get a list of routes.
*
* If the list is not empty, the route at index 0 is the one treated as the primary route
* and used for route progress, off route events and map-matching calculations.
*
* @return a list of [DirectionsRoute]s
*/
fun getRoutes() = directionsSession.routes
/**
* Call this method whenever this instance of the [MapboxNavigation] is not going to be used anymore and should release all of its resources.
*/
fun onDestroy() {
logger.d(
Tag(MapboxNavigationTelemetry.TAG),
Message("onDestroy")
)
MapboxNavigationTelemetry.unregisterListeners(this@MapboxNavigation)
directionsSession.shutdown()
directionsSession.unregisterAllRoutesObservers()
tripSession.stop()
tripSession.unregisterAllLocationObservers()
tripSession.unregisterAllRouteProgressObservers()
tripSession.unregisterAllOffRouteObservers()
tripSession.unregisterAllStateObservers()
tripSession.unregisterAllBannerInstructionsObservers()
tripSession.unregisterAllVoiceInstructionsObservers()
tripSession.route = null
// TODO replace this with a destroy when nav-native has a destructor
navigator.create(navigationOptions.deviceProfile, logger)
navigationSession.unregisterAllNavigationSessionStateObservers()
fasterRouteController.stop()
routeRefreshController.stop()
ThreadController.cancelAllNonUICoroutines()
ThreadController.cancelAllUICoroutines()
}
/**
* API used to retrieve logged location and route progress samples for debug purposes.
*
* @return history trace string
*/
fun retrieveHistory(): String {
return MapboxNativeNavigatorImpl.getHistory()
}
/**
* API used to enable/disable location and route progress samples logs for debug purposes.
*/
fun toggleHistory(isEnabled: Boolean) {
MapboxNativeNavigatorImpl.toggleHistory(isEnabled)
}
/**
* API used to artificially add debug events to logs.
*/
fun addHistoryEvent(eventType: String, eventJsonProperties: String) {
MapboxNativeNavigatorImpl.addHistoryEvent(eventType, eventJsonProperties)
}
/**
* API used to retrieve the SSML announcement for voice instructions.
*
* @return SSML voice instruction announcement string
*/
fun retrieveSsmlAnnouncementInstruction(index: Int): String? =
MapboxNativeNavigatorImpl.getVoiceInstruction(index)?.ssmlAnnouncement
/**
* Registers [LocationObserver]. The updates are available whenever the trip session is started.
*
* @see [startTripSession]
*/
fun registerLocationObserver(locationObserver: LocationObserver) {
tripSession.registerLocationObserver(locationObserver)
}
/**
* Unregisters [LocationObserver].
*/
fun unregisterLocationObserver(locationObserver: LocationObserver) {
tripSession.unregisterLocationObserver(locationObserver)
}
/**
* Registers [RouteProgressObserver]. The updates are available whenever the trip session is started and a primary route is available.
*
* @see [startTripSession]
* @see [requestRoutes] // TODO add route setter
*/
fun registerRouteProgressObserver(routeProgressObserver: RouteProgressObserver) {
tripSession.registerRouteProgressObserver(routeProgressObserver)
}
/**
* Unregisters [RouteProgressObserver].
*/
fun unregisterRouteProgressObserver(routeProgressObserver: RouteProgressObserver) {
tripSession.unregisterRouteProgressObserver(routeProgressObserver)
}
/**
* Registers [OffRouteObserver]. The updates are available whenever SDK is in an `Active Guidance` state and detects an off route event.
* The SDK will automatically request redirected route.
*/
fun registerOffRouteObserver(offRouteObserver: OffRouteObserver) {
tripSession.registerOffRouteObserver(offRouteObserver)
}
/**
* Unregisters [OffRouteObserver].
*/
fun unregisterOffRouteObserver(offRouteObserver: OffRouteObserver) {
tripSession.unregisterOffRouteObserver(offRouteObserver)
}
/**
* Registers [RoutesObserver]. The updates are available when a new list of routes is set.
* The route at index 0, if exist, will be treated as the primary route for 'Active Guidance' and location map-matching.
*/
fun registerRoutesObserver(routesObserver: RoutesObserver) {
directionsSession.registerRoutesObserver(routesObserver)
}
/**
* Unregisters [RoutesObserver].
*/
fun unregisterRoutesObserver(routesObserver: RoutesObserver) {
directionsSession.unregisterRoutesObserver(routesObserver)
}
/**
* Registers [BannerInstructionsObserver]. The updates are available whenever SDK is in an `Active Guidance` state.
* The SDK will push this event only once per route step.
*/
fun registerBannerInstructionsObserver(bannerInstructionsObserver: BannerInstructionsObserver) {
tripSession.registerBannerInstructionsObserver(bannerInstructionsObserver)
}
/**
* Unregisters [BannerInstructionsObserver].
*/
fun unregisterBannerInstructionsObserver(bannerInstructionsObserver: BannerInstructionsObserver) {
tripSession.unregisterBannerInstructionsObserver(bannerInstructionsObserver)
}
/**
* Registers [VoiceInstructionsObserver]. The updates are available whenever SDK is in an `Active Guidance` state.
* The SDK will push this event only once per route step.
*/
fun registerVoiceInstructionsObserver(voiceInstructionsObserver: VoiceInstructionsObserver) {
tripSession.registerVoiceInstructionsObserver(voiceInstructionsObserver)
}
/**
* Unregisters [VoiceInstructionsObserver].
*/
fun unregisterVoiceInstructionsObserver(voiceInstructionsObserver: VoiceInstructionsObserver) {
tripSession.unregisterVoiceInstructionsObserver(voiceInstructionsObserver)
}
/**
* Registers [TripSessionStateObserver]. Monitors the trip session's state.
*
* @see [startTripSession]
* @see [stopTripSession]
*/
fun registerTripSessionStateObserver(tripSessionStateObserver: TripSessionStateObserver) {
tripSession.registerStateObserver(tripSessionStateObserver)
}
/**
* Unregisters [TripSessionStateObserver].
*/
fun unregisterTripSessionStateObserver(tripSessionStateObserver: TripSessionStateObserver) {
tripSession.unregisterStateObserver(tripSessionStateObserver)
}
/**
* Set your own controller to determine when drivers arrived at stops via [ArrivalController].
* Use [navigateNextRouteLeg] to manually move navigator to the next stop. To reset to the
* automatic arrival controller, call [setArrivalController].
*
* By default uses [AutoArrivalController].
*
* Set *null* disables arrival at stops completely. Use this if you want to write your
* own mechanism for handling arrival at stops.
*
* @param arrivalController [ArrivalController]
*/
@JvmOverloads
fun setArrivalController(arrivalController: ArrivalController? = AutoArrivalController()) {
if (arrivalController == null) {
tripSession.unregisterRouteProgressObserver(arrivalProgressObserver)
} else {
arrivalProgressObserver.attach(arrivalController)
tripSession.registerRouteProgressObserver(arrivalProgressObserver)
}
}
/**
* Set [RerouteController]. By default uses [MapboxRerouteController].
*
* Set *null* disables auto-reroute.
*/
fun setRerouteController(rerouteController: RerouteController?) {
val legacyRerouteController = this.rerouteController
this.rerouteController = rerouteController
if (legacyRerouteController?.state == RerouteState.FetchingRoute) {
legacyRerouteController.interrupt()
reroute()
}
}
/**
* Get [RerouteController]
*/
fun getRerouteController(): RerouteController? = rerouteController
/**
* Registers [ArrivalObserver]. Monitor arrival at stops and destinations. For more control
* of arrival at stops, see [setArrivalController].
*
* @see [unregisterArrivalObserver]
*/
fun registerArrivalObserver(arrivalObserver: ArrivalObserver) {
arrivalProgressObserver.registerObserver(arrivalObserver)
}
/**
* Unregisters [ArrivalObserver].
*
* @see [registerArrivalObserver]
*/
fun unregisterArrivalObserver(arrivalObserver: ArrivalObserver) {
arrivalProgressObserver.unregisterObserver(arrivalObserver)
}
/**
* After arriving at a stop, this can be used to manually decide when to start
* navigating to the next stop. Use the [ArrivalController] to control when to
* call [navigateNextRouteLeg].
*
* @return true if navigation to next stop could be started, false otherwise
*/
fun navigateNextRouteLeg(): Boolean {
return arrivalProgressObserver.navigateNextRouteLeg()
}
/**
* Start observing faster routes for a trip session via [FasterRouteObserver]
*
* @param fasterRouteObserver FasterRouteObserver
*/
fun attachFasterRouteObserver(fasterRouteObserver: FasterRouteObserver) {
fasterRouteController.attach(fasterRouteObserver)
}
/**
* Stop observing the possibility of faster routes.
*/
fun detachFasterRouteObserver() {
fasterRouteController.stop()
}
/**
* Register a [NavigationSessionStateObserver] to be notified of the various Session states. Not publicly available
*/
internal fun registerNavigationSessionObserver(navigationSessionStateObserver: NavigationSessionStateObserver) {
navigationSession.registerNavigationSessionStateObserver(navigationSessionStateObserver)
}
/**
* Unregisters a [NavigationSessionStateObserver]. Not publicly available
*/
internal fun unregisterNavigationSessionObserver(navigationSessionStateObserver: NavigationSessionStateObserver) {
navigationSession.unregisterNavigationSessionStateObserver(navigationSessionStateObserver)
}
private fun createInternalRoutesObserver() = object : RoutesObserver {
override fun onRoutesChanged(routes: List<DirectionsRoute>) {
if (routes.isNotEmpty()) {
tripSession.route = routes[0]
} else {
tripSession.route = null
}
}
}
private fun createInternalOffRouteObserver() = object : OffRouteObserver {
override fun onOffRouteStateChanged(offRoute: Boolean) {
if (offRoute) {
reroute()
} else {
rerouteController?.interrupt()
}
}
}
private fun reroute() {
rerouteController?.reroute(object : RerouteController.RoutesCallback {
override fun onNewRoutes(routes: List<DirectionsRoute>) {
setRoutes(routes)
}
})
}
private fun obtainUserAgent(isFromNavigationUi: Boolean): String {
return if (isFromNavigationUi) {
"$MAPBOX_NAVIGATION_UI_USER_AGENT_BASE/${BuildConfig.MAPBOX_NAVIGATION_VERSION_NAME}"
} else {
"$MAPBOX_NAVIGATION_USER_AGENT_BASE/${BuildConfig.MAPBOX_NAVIGATION_VERSION_NAME}"
}
}
private fun monitorNotificationActionButton(channel: ReceiveChannel<NotificationAction>) {
mainJobController.scope.monitorChannelWithException(channel, { notificationAction ->
when (notificationAction) {
NotificationAction.END_NAVIGATION -> tripSession.stop()
}
})
}
/**
* Provides parameters for Mapbox default modules, recursively if a module depends on other Mapbox modules.
*/
private fun paramsProvider(type: MapboxModuleType): Array<Pair<Class<*>?, Any?>> {
return when (type) {
MapboxModuleType.NavigationRouter -> arrayOf(
Router::class.java to MapboxModuleProvider.createModule(
MapboxModuleType.NavigationOnboardRouter,
::paramsProvider
),
Router::class.java to MapboxModuleProvider.createModule(
MapboxModuleType.NavigationOffboardRouter,
::paramsProvider
),
NetworkStatusService::class.java to NetworkStatusService(navigationOptions.applicationContext)
)
MapboxModuleType.NavigationOffboardRouter -> arrayOf(
String::class.java to (accessToken
?: throw RuntimeException(MAPBOX_NAVIGATION_TOKEN_EXCEPTION_OFFBOARD_ROUTER)),
Context::class.java to navigationOptions.applicationContext,
UrlSkuTokenProvider::class.java to MapboxNavigationAccounts.getInstance(navigationOptions.applicationContext)
)
MapboxModuleType.NavigationOnboardRouter -> {
check(accessToken != null) { MAPBOX_NAVIGATION_TOKEN_EXCEPTION_ONBOARD_ROUTER }
arrayOf(
Context::class.java to navigationOptions.applicationContext,
String::class.java to accessToken,
MapboxNativeNavigator::class.java to MapboxNativeNavigatorImpl,
OnboardRouterOptions::class.java to navigationOptions.onboardRouterOptions,
Logger::class.java to logger,
SkuTokenProvider::class.java to MapboxNavigationAccounts.getInstance(navigationOptions.applicationContext)
)
}
MapboxModuleType.NavigationTripNotification -> arrayOf(
NavigationOptions::class.java to navigationOptions
)
MapboxModuleType.CommonLogger -> arrayOf()
MapboxModuleType.CommonLibraryLoader -> throw IllegalArgumentException("not supported: $type")
MapboxModuleType.CommonHttpClient -> throw IllegalArgumentException("not supported: $type")
}
}
/**
* Sends an event to improve navigation positioning. See SensorEventEmitter to register
*
* @param sensorEvent the Android sensor event, it will be ignored if it is not recognized
*/
fun updateSensorEvent(sensorEvent: SensorEvent) {
tripSession.updateSensorEvent(sensorEvent)
}
/**
* Updates the configuration to enable or disable the extended kalman filter (EKF).
*
* @param useEKF the new value for EKF
*/
fun useExtendedKalmanFilter(useEKF: Boolean) {
tripSession.useExtendedKalmanFilter(useEKF)
}
companion object {
/**
* Send user feedback about an issue or problem with the Navigation SDK
*
* @param feedbackType one of [FeedbackEvent.Type]
* @param description description message
* @param feedbackSource one of [FeedbackEvent.Source]
* @param screenshot encoded screenshot (optional)
* @param feedbackSubType array of [FeedbackEvent.Description] (optional)
*/
@JvmStatic
fun postUserFeedback(
@FeedbackEvent.Type feedbackType: String,
description: String,
@FeedbackEvent.Source feedbackSource: String,
screenshot: String?,
feedbackSubType: Array<String>? = emptyArray()
) {
MapboxNavigationTelemetry.postUserFeedback(
feedbackType,
description,
feedbackSource,
screenshot,
feedbackSubType
)
}
/**
* Returns a pre-build set of [NavigationOptions] with smart defaults.
*
* Use [NavigationOptions.toBuilder] to easily customize selected options.
*
* @param context [Context]
* @param accessToken Mapbox access token
* @return default [NavigationOptions]
*/
@JvmStatic
fun defaultNavigationOptionsBuilder(context: Context, accessToken: String?): NavigationOptions.Builder {
val distanceFormatter = MapboxDistanceFormatter.builder()
.withUnitType(VoiceUnit.UNDEFINED)
.withRoundingIncrement(Rounding.INCREMENT_FIFTY)
.build(context)
return NavigationOptions.Builder(context)
.accessToken(accessToken)
.distanceFormatter(distanceFormatter)
}
}
}