diff --git a/app/src/main/java/com/mapbox/services/android/navigation/testapp/activity/MockNavigationActivity.java b/app/src/main/java/com/mapbox/services/android/navigation/testapp/activity/MockNavigationActivity.java
index f5d637df743..f10c5cb820d 100644
--- a/app/src/main/java/com/mapbox/services/android/navigation/testapp/activity/MockNavigationActivity.java
+++ b/app/src/main/java/com/mapbox/services/android/navigation/testapp/activity/MockNavigationActivity.java
@@ -16,6 +16,8 @@
import android.widget.Toast;
import com.mapbox.android.core.location.LocationEngine;
+import com.mapbox.android.core.location.LocationEngineCallback;
+import com.mapbox.android.core.location.LocationEngineResult;
import com.mapbox.api.directions.v5.models.DirectionsResponse;
import com.mapbox.api.directions.v5.models.DirectionsRoute;
import com.mapbox.geojson.Point;
@@ -28,6 +30,7 @@
import com.mapbox.mapboxsdk.maps.MapView;
import com.mapbox.mapboxsdk.maps.MapboxMap;
import com.mapbox.mapboxsdk.maps.OnMapReadyCallback;
+import com.mapbox.mapboxsdk.maps.Style;
import com.mapbox.services.android.navigation.testapp.R;
import com.mapbox.services.android.navigation.testapp.Utils;
import com.mapbox.services.android.navigation.testapp.activity.notification.CustomNavigationNotification;
@@ -170,25 +173,24 @@ private void newOrigin() {
@SuppressLint("MissingPermission")
@Override
- public void onMapReady(MapboxMap mapboxMap) {
+ public void onMapReady(@NonNull MapboxMap mapboxMap) {
this.mapboxMap = mapboxMap;
-
- LocationComponent locationComponent = mapboxMap.getLocationComponent();
- locationComponent.activateLocationComponent(this);
- locationComponent.setRenderMode(RenderMode.GPS);
- locationComponent.setLocationComponentEnabled(false);
- navigationMapRoute = new NavigationMapRoute(navigation, mapView, mapboxMap);
-
- mapboxMap.addOnMapClickListener(this);
- Snackbar.make(findViewById(R.id.container), "Tap map to place waypoint", BaseTransientBottomBar.LENGTH_LONG).show();
-
- locationEngine = new ReplayRouteLocationEngine();
-
- newOrigin();
+ this.mapboxMap.addOnMapClickListener(this);
+ mapboxMap.setStyle(Style.MAPBOX_STREETS, style -> {
+ LocationComponent locationComponent = mapboxMap.getLocationComponent();
+ locationComponent.activateLocationComponent(this, style);
+ locationComponent.setRenderMode(RenderMode.GPS);
+ locationComponent.setLocationComponentEnabled(false);
+ navigationMapRoute = new NavigationMapRoute(navigation, mapView, mapboxMap);
+ Snackbar.make(findViewById(R.id.container), "Tap map to place waypoint",
+ BaseTransientBottomBar.LENGTH_LONG).show();
+ locationEngine = new ReplayRouteLocationEngine();
+ newOrigin();
+ });
}
@Override
- public void onMapClick(@NonNull LatLng point) {
+ public boolean onMapClick(@NonNull LatLng point) {
if (destination == null) {
destination = Point.fromLngLat(point.getLongitude(), point.getLatitude());
} else if (waypoint == null) {
@@ -198,15 +200,30 @@ public void onMapClick(@NonNull LatLng point) {
}
mapboxMap.addMarker(new MarkerOptions().position(point));
calculateRoute();
+ return true;
}
+ @SuppressLint("MissingPermission")
private void calculateRoute() {
- Location userLocation = locationEngine.getLastLocation();
+ locationEngine.getLastLocation(new LocationEngineCallback() {
+ @Override
+ public void onSuccess(LocationEngineResult result) {
+ findRouteWith(result);
+ }
+
+ @Override
+ public void onFailure(@NonNull Exception exception) {
+ Timber.e(exception);
+ }
+ });
+ }
+
+ private void findRouteWith(LocationEngineResult result) {
+ Location userLocation = result.getLastLocation();
if (userLocation == null) {
Timber.d("calculateRoute: User location is null, therefore, origin can't be set.");
return;
}
-
Point origin = Point.fromLngLat(userLocation.getLongitude(), userLocation.getLatitude());
if (TurfMeasurement.distance(origin, destination, TurfConstants.UNIT_METERS) < 50) {
startRouteButton.setVisibility(View.GONE);
@@ -223,12 +240,11 @@ private void calculateRoute() {
navigationRouteBuilder.build().getRoute(new Callback() {
@Override
- public void onResponse(Call call, Response response) {
+ public void onResponse(@NonNull Call call, @NonNull Response response) {
Timber.d("Url: %s", call.request().url().toString());
if (response.body() != null) {
if (!response.body().routes().isEmpty()) {
- DirectionsRoute directionsRoute = response.body().routes().get(0);
- MockNavigationActivity.this.route = directionsRoute;
+ MockNavigationActivity.this.route = response.body().routes().get(0);
navigationMapRoute.addRoutes(response.body().routes());
startRouteButton.setVisibility(View.VISIBLE);
}
@@ -236,7 +252,7 @@ public void onResponse(Call call, Response call, Throwable throwable) {
+ public void onFailure(@NonNull Call call, @NonNull Throwable throwable) {
Timber.e(throwable, "onFailure: navigation.getRoute()");
}
});
@@ -310,8 +326,6 @@ public void onLowMemory() {
protected void onDestroy() {
super.onDestroy();
navigation.onDestroy();
- locationEngine.removeLocationUpdates();
- locationEngine.deactivate();
if (mapboxMap != null) {
mapboxMap.removeOnMapClickListener(this);
}
diff --git a/app/src/main/java/com/mapbox/services/android/navigation/testapp/activity/OfflineRegionDownloadActivity.kt b/app/src/main/java/com/mapbox/services/android/navigation/testapp/activity/OfflineRegionDownloadActivity.kt
index 6bca5884ff8..ea9ad979690 100644
--- a/app/src/main/java/com/mapbox/services/android/navigation/testapp/activity/OfflineRegionDownloadActivity.kt
+++ b/app/src/main/java/com/mapbox/services/android/navigation/testapp/activity/OfflineRegionDownloadActivity.kt
@@ -19,6 +19,7 @@ import android.widget.Toast
import com.mapbox.geojson.BoundingBox
import com.mapbox.mapboxsdk.Mapbox
import com.mapbox.mapboxsdk.maps.MapboxMap
+import com.mapbox.mapboxsdk.maps.Style
import com.mapbox.mapboxsdk.style.layers.FillLayer
import com.mapbox.mapboxsdk.style.layers.PropertyFactory.fillColor
import com.mapbox.mapboxsdk.style.sources.GeoJsonSource
@@ -113,17 +114,13 @@ class OfflineRegionDownloadActivity : AppCompatActivity(), RouteTileDownloadList
private fun setupMapView(savedInstanceState: Bundle?) {
mapView.onCreate(savedInstanceState)
mapView.getMapAsync { mapboxMap ->
+ mapboxMap.setStyle(Style.LIGHT) {
+ it.addSource(GeoJsonSource("bounding-box-source"))
+ it.addLayer(FillLayer("bounding-box-layer", "bounding-box-source")
+ .withProperties(fillColor(Color.parseColor("#50667F"))))
+ }
this.mapboxMap = mapboxMap
mapboxMap.uiSettings.isRotateGesturesEnabled = false
- addBoundingBoxToMap()
- }
- }
-
- private fun addBoundingBoxToMap() {
- mapboxMap.apply {
- addSource(GeoJsonSource("bounding-box-source"))
- addLayer(FillLayer("bounding-box-layer", "bounding-box-source")
- .withProperties(fillColor(Color.parseColor("#50667F"))))
}
}
diff --git a/app/src/main/java/com/mapbox/services/android/navigation/testapp/activity/RerouteActivity.java b/app/src/main/java/com/mapbox/services/android/navigation/testapp/activity/RerouteActivity.java
index 3ca8bfa35fe..2767ecb67aa 100644
--- a/app/src/main/java/com/mapbox/services/android/navigation/testapp/activity/RerouteActivity.java
+++ b/app/src/main/java/com/mapbox/services/android/navigation/testapp/activity/RerouteActivity.java
@@ -9,7 +9,8 @@
import android.view.View;
import android.widget.Toast;
-import com.mapbox.android.core.location.LocationEngineListener;
+import com.mapbox.android.core.location.LocationEngineCallback;
+import com.mapbox.android.core.location.LocationEngineResult;
import com.mapbox.api.directions.v5.models.DirectionsResponse;
import com.mapbox.api.directions.v5.models.DirectionsRoute;
import com.mapbox.core.constants.Constants;
@@ -27,6 +28,7 @@
import com.mapbox.mapboxsdk.maps.MapView;
import com.mapbox.mapboxsdk.maps.MapboxMap;
import com.mapbox.mapboxsdk.maps.OnMapReadyCallback;
+import com.mapbox.mapboxsdk.maps.Style;
import com.mapbox.services.android.navigation.testapp.R;
import com.mapbox.services.android.navigation.ui.v5.instruction.InstructionView;
import com.mapbox.services.android.navigation.v5.location.replay.ReplayRouteLocationEngine;
@@ -41,6 +43,7 @@
import com.mapbox.services.android.navigation.v5.routeprogress.ProgressChangeListener;
import com.mapbox.services.android.navigation.v5.routeprogress.RouteProgress;
+import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;
@@ -51,9 +54,9 @@
import retrofit2.Response;
import timber.log.Timber;
-public class RerouteActivity extends HistoryActivity implements OnMapReadyCallback, LocationEngineListener,
- Callback, MapboxMap.OnMapClickListener, NavigationEventListener, OffRouteListener,
- ProgressChangeListener, MilestoneEventListener {
+public class RerouteActivity extends HistoryActivity implements OnMapReadyCallback,
+ Callback, MapboxMap.OnMapClickListener, NavigationEventListener,
+ OffRouteListener, ProgressChangeListener, MilestoneEventListener {
@BindView(R.id.mapView)
MapView mapView;
@@ -66,6 +69,8 @@ public class RerouteActivity extends HistoryActivity implements OnMapReadyCallba
private Point destination = Point.fromLngLat(-0.383524, 39.497825);
private Polyline polyline;
+ private final RerouteActivityLocationCallback callback = new RerouteActivityLocationCallback(this);
+ private Location lastLocation;
private ReplayRouteLocationEngine mockLocationEngine;
private MapboxNavigation navigation;
private MapboxMap mapboxMap;
@@ -141,47 +146,34 @@ protected void onDestroy() {
@SuppressLint("MissingPermission")
@Override
- public void onMapReady(MapboxMap mapboxMap) {
+ public void onMapReady(@NonNull MapboxMap mapboxMap) {
this.mapboxMap = mapboxMap;
- mapboxMap.addOnMapClickListener(this);
-
- LocationComponent locationComponent = mapboxMap.getLocationComponent();
- locationComponent.activateLocationComponent(this);
- locationComponent.setLocationComponentEnabled(true);
- locationComponent.setRenderMode(RenderMode.GPS);
-
- mockLocationEngine = new ReplayRouteLocationEngine();
- mockLocationEngine.addLocationEngineListener(this);
- navigation.setLocationEngine(mockLocationEngine);
-
- getRoute(origin, destination, null);
+ this.mapboxMap.addOnMapClickListener(this);
+ mapboxMap.setStyle(Style.DARK, style -> {
+ LocationComponent locationComponent = mapboxMap.getLocationComponent();
+ locationComponent.activateLocationComponent(this, style);
+ locationComponent.setLocationComponentEnabled(true);
+ locationComponent.setRenderMode(RenderMode.GPS);
+
+ mockLocationEngine = new ReplayRouteLocationEngine();
+ getRoute(origin, destination);
+ });
}
@Override
- public void onConnected() {
- // No-op - mock automatically begins pushing updates
- }
-
- @Override
- public void onLocationChanged(Location location) {
- if (!tracking) {
- mapboxMap.getLocationComponent().forceLocationUpdate(location);
- }
- }
-
- @Override
- public void onMapClick(@NonNull LatLng point) {
- if (!running || mapboxMap == null) {
- return;
+ public boolean onMapClick(@NonNull LatLng point) {
+ if (!running || mapboxMap == null || lastLocation == null) {
+ return true;
}
mapboxMap.addMarker(new MarkerOptions().position(point));
mapboxMap.removeOnMapClickListener(this);
- Point newDestination = Point.fromLngLat(point.getLongitude(), point.getLatitude());
- mockLocationEngine.moveTo(newDestination);
destination = Point.fromLngLat(point.getLongitude(), point.getLatitude());
+ resetLocationEngine(destination);
+
tracking = false;
+ return true;
}
@Override
@@ -195,8 +187,8 @@ public void onRunning(boolean running) {
@Override
public void userOffRoute(Location location) {
- Point newOrigin = Point.fromLngLat(location.getLongitude(), location.getLatitude());
- getRoute(newOrigin, destination, location.getBearing());
+ origin = Point.fromLngLat(lastLocation.getLongitude(), lastLocation.getLatitude());
+ getRoute(origin, destination);
Snackbar.make(contentLayout, "User Off Route", Snackbar.LENGTH_SHORT).show();
mapboxMap.addMarker(new MarkerOptions().position(new LatLng(location.getLatitude(), location.getLongitude())));
}
@@ -204,6 +196,7 @@ public void userOffRoute(Location location) {
@Override
public void onProgressChange(Location location, RouteProgress routeProgress) {
boolean isInTunnel = routeProgress.inTunnel();
+ lastLocation = location;
if (!wasInTunnel && isInTunnel) {
wasInTunnel = true;
Snackbar.make(contentLayout, "Enter tunnel!", Snackbar.LENGTH_SHORT).show();
@@ -230,11 +223,11 @@ public void onMilestoneEvent(RouteProgress routeProgress, String instruction, Mi
Snackbar.make(contentLayout, instruction, Snackbar.LENGTH_SHORT).show();
}
instructionView.updateBannerInstructionsWith(milestone);
- Timber.d("onMilestoneEvent - Current Instruction: " + instruction);
+ Timber.d("onMilestoneEvent - Current Instruction: %s", instruction);
}
@Override
- public void onResponse(Call call, Response response) {
+ public void onResponse(@NonNull Call call, @NonNull Response response) {
Timber.d(call.request().url().toString());
if (response.body() != null) {
if (!response.body().routes().isEmpty()) {
@@ -249,14 +242,19 @@ public void onResponse(Call call, Response call, Throwable throwable) {
+ public void onFailure(@NonNull Call call, @NonNull Throwable throwable) {
Timber.e(throwable);
}
- private void getRoute(Point origin, Point destination, Float bearing) {
- Double heading = bearing == null ? null : bearing.doubleValue();
+ void updateLocation(Location location) {
+ if (!tracking) {
+ mapboxMap.getLocationComponent().forceLocationUpdate(location);
+ }
+ }
+
+ private void getRoute(Point origin, Point destination) {
NavigationRoute.builder(this)
- .origin(origin, heading, 90d)
+ .origin(origin)
.destination(destination)
.accessToken(Mapbox.getAccessToken())
.build().getRoute(this);
@@ -281,16 +279,19 @@ private void drawRoute(DirectionsRoute route) {
}
}
+ private void resetLocationEngine(Point point) {
+ mockLocationEngine.moveTo(point);
+ navigation.setLocationEngine(mockLocationEngine);
+ }
+
private void resetLocationEngine(DirectionsRoute directionsRoute) {
- mockLocationEngine.deactivate();
mockLocationEngine.assign(directionsRoute);
+ navigation.setLocationEngine(mockLocationEngine);
}
private void shutdownLocationEngine() {
if (mockLocationEngine != null) {
- mockLocationEngine.removeLocationEngineListener(this);
- mockLocationEngine.removeLocationUpdates();
- mockLocationEngine.deactivate();
+ mockLocationEngine.removeLocationUpdates(callback);
}
}
@@ -299,4 +300,30 @@ private void shutdownNavigation() {
navigation.removeProgressChangeListener(this);
navigation.onDestroy();
}
+
+ private static class RerouteActivityLocationCallback implements LocationEngineCallback {
+
+ private final WeakReference activityWeakReference;
+
+ RerouteActivityLocationCallback(RerouteActivity activity) {
+ this.activityWeakReference = new WeakReference<>(activity);
+ }
+
+ @Override
+ public void onSuccess(LocationEngineResult result) {
+ RerouteActivity activity = activityWeakReference.get();
+ if (activity != null) {
+ Location location = result.getLastLocation();
+ if (location == null) {
+ return;
+ }
+ activity.updateLocation(location);
+ }
+ }
+
+ @Override
+ public void onFailure(@NonNull Exception exception) {
+ Timber.e(exception);
+ }
+ }
}
\ No newline at end of file
diff --git a/app/src/main/java/com/mapbox/services/android/navigation/testapp/activity/location/ForwardingLocationCallback.java b/app/src/main/java/com/mapbox/services/android/navigation/testapp/activity/location/ForwardingLocationCallback.java
deleted file mode 100644
index eeec7bbf064..00000000000
--- a/app/src/main/java/com/mapbox/services/android/navigation/testapp/activity/location/ForwardingLocationCallback.java
+++ /dev/null
@@ -1,28 +0,0 @@
-package com.mapbox.services.android.navigation.testapp.activity.location;
-
-import android.location.Location;
-
-import com.google.android.gms.location.LocationCallback;
-import com.google.android.gms.location.LocationResult;
-
-import java.util.List;
-
-class ForwardingLocationCallback extends LocationCallback {
-
- private static final int FIRST = 0;
- private final FusedLocationEngine locationEngine;
-
- ForwardingLocationCallback(FusedLocationEngine locationEngine) {
- this.locationEngine = locationEngine;
- }
-
- @Override
- public void onLocationResult(LocationResult locationResult) {
- List locations = locationResult.getLocations();
- boolean hasLocation = !locations.isEmpty();
- if (hasLocation) {
- Location newLocation = locations.get(FIRST);
- locationEngine.notifyListenersOnLocationChanged(newLocation);
- }
- }
-}
diff --git a/app/src/main/java/com/mapbox/services/android/navigation/testapp/activity/location/FusedLocationEngine.java b/app/src/main/java/com/mapbox/services/android/navigation/testapp/activity/location/FusedLocationEngine.java
deleted file mode 100644
index 30188bc0114..00000000000
--- a/app/src/main/java/com/mapbox/services/android/navigation/testapp/activity/location/FusedLocationEngine.java
+++ /dev/null
@@ -1,137 +0,0 @@
-package com.mapbox.services.android.navigation.testapp.activity.location;
-
-import android.content.Context;
-import android.location.Location;
-import android.os.Looper;
-import android.support.annotation.NonNull;
-
-import com.google.android.gms.common.api.ApiException;
-import com.google.android.gms.location.FusedLocationProviderClient;
-import com.google.android.gms.location.LocationRequest;
-import com.google.android.gms.location.LocationServices;
-import com.google.android.gms.location.LocationSettingsRequest;
-import com.google.android.gms.location.LocationSettingsStatusCodes;
-import com.google.android.gms.location.SettingsClient;
-import com.mapbox.android.core.location.LocationEngine;
-import com.mapbox.android.core.location.LocationEngineListener;
-
-import timber.log.Timber;
-
-public class FusedLocationEngine extends LocationEngine {
-
- private static final long UPDATE_INTERVAL_IN_MILLISECONDS = 1000;
- private static final long FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS = 500;
- private FusedLocationProviderClient fusedLocationClient;
- private SettingsClient settingsClient;
- private LocationRequest locationRequest;
- private LocationSettingsRequest locationSettingsRequest;
- private boolean isConnected = false;
- private boolean receivingUpdates = false;
- private Location lastLocation = null;
- private final ForwardingLocationCallback forwardingCallback = new ForwardingLocationCallback(this);
-
- public FusedLocationEngine(@NonNull Context context) {
- super();
- fusedLocationClient = LocationServices.getFusedLocationProviderClient(context);
- settingsClient = LocationServices.getSettingsClient(context);
- }
-
- @Override
- public void activate() {
- if (!isConnected) {
- startLocationUpdates();
- }
- }
-
- @Override
- public void deactivate() {
- stopLocationUpdates();
- isConnected = false;
- }
-
- @Override
- public boolean isConnected() {
- return isConnected;
- }
-
- @Override
- @SuppressWarnings("MissingPermission")
- public Location getLastLocation() {
- fusedLocationClient.getLastLocation().addOnSuccessListener(location -> lastLocation = location);
- return lastLocation;
- }
-
- @Override
- @SuppressWarnings( {"MissingPermission"})
- public void requestLocationUpdates() {
- if (isConnected && !receivingUpdates) {
- fusedLocationClient.requestLocationUpdates(locationRequest, forwardingCallback, Looper.myLooper())
- .addOnSuccessListener(aVoid -> receivingUpdates = true);
- }
- }
-
- @Override
- public void removeLocationUpdates() {
- stopLocationUpdates();
- }
-
- @Override
- public Type obtainType() {
- return Type.GOOGLE_PLAY_SERVICES;
- }
-
- void notifyListenersOnLocationChanged(Location location) {
- for (LocationEngineListener listener : locationListeners) {
- listener.onLocationChanged(location);
- }
- }
-
- private void createLocationRequest() {
- locationRequest = new LocationRequest();
- //TODO: unhardcode these
- locationRequest.setInterval(UPDATE_INTERVAL_IN_MILLISECONDS);
- locationRequest.setFastestInterval(FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS);
- locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
- }
-
- private void buildLocationSettingsRequest() {
- LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder();
- builder.addLocationRequest(locationRequest);
- locationSettingsRequest = builder.build();
- }
-
- private void startLocationUpdates() {
- createLocationRequest();
- buildLocationSettingsRequest();
- settingsClient.checkLocationSettings(locationSettingsRequest)
- .addOnSuccessListener(locationSettingsResponse -> {
- isConnected = true;
- notifyListenersOnConnected();
- })
- .addOnFailureListener(exception -> {
- isConnected = false;
- int statusCode = ((ApiException) exception).getStatusCode();
- switch (statusCode) {
- case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
- Timber.e("Location settings are not satisfied. Upgrade location settings");
- break;
- case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
- Timber.e("Location settings are inadequate, and cannot be fixed here. Fix in Settings.");
- break;
- default:
- break;
- }
- });
- }
-
- private void notifyListenersOnConnected() {
- for (LocationEngineListener listener : locationListeners) {
- listener.onConnected();
- }
- }
-
- private void stopLocationUpdates() {
- fusedLocationClient.removeLocationUpdates(forwardingCallback)
- .addOnCompleteListener(task -> receivingUpdates = false);
- }
-}
diff --git a/app/src/main/java/com/mapbox/services/android/navigation/testapp/activity/navigationui/ComponentNavigationActivity.java b/app/src/main/java/com/mapbox/services/android/navigation/testapp/activity/navigationui/ComponentNavigationActivity.java
index 20eefebb1aa..1e15bdef18a 100644
--- a/app/src/main/java/com/mapbox/services/android/navigation/testapp/activity/navigationui/ComponentNavigationActivity.java
+++ b/app/src/main/java/com/mapbox/services/android/navigation/testapp/activity/navigationui/ComponentNavigationActivity.java
@@ -17,8 +17,10 @@
import android.view.View;
import com.mapbox.android.core.location.LocationEngine;
-import com.mapbox.android.core.location.LocationEngineListener;
-import com.mapbox.android.core.location.LocationEnginePriority;
+import com.mapbox.android.core.location.LocationEngineCallback;
+import com.mapbox.android.core.location.LocationEngineProvider;
+import com.mapbox.android.core.location.LocationEngineRequest;
+import com.mapbox.android.core.location.LocationEngineResult;
import com.mapbox.api.directions.v5.models.DirectionsResponse;
import com.mapbox.api.directions.v5.models.DirectionsRoute;
import com.mapbox.geojson.Point;
@@ -30,9 +32,9 @@
import com.mapbox.mapboxsdk.maps.MapView;
import com.mapbox.mapboxsdk.maps.MapboxMap;
import com.mapbox.mapboxsdk.maps.OnMapReadyCallback;
+import com.mapbox.mapboxsdk.maps.Style;
import com.mapbox.services.android.navigation.testapp.R;
import com.mapbox.services.android.navigation.testapp.activity.HistoryActivity;
-import com.mapbox.services.android.navigation.testapp.activity.location.FusedLocationEngine;
import com.mapbox.services.android.navigation.ui.v5.camera.DynamicCamera;
import com.mapbox.services.android.navigation.ui.v5.camera.NavigationCamera;
import com.mapbox.services.android.navigation.ui.v5.instruction.InstructionView;
@@ -51,6 +53,7 @@
import com.mapbox.services.android.navigation.v5.routeprogress.RouteProgress;
import java.io.File;
+import java.lang.ref.WeakReference;
import java.util.List;
import java.util.Locale;
@@ -64,8 +67,7 @@
import timber.log.Timber;
public class ComponentNavigationActivity extends HistoryActivity implements OnMapReadyCallback,
- MapboxMap.OnMapLongClickListener, LocationEngineListener, ProgressChangeListener,
- MilestoneEventListener, OffRouteListener {
+ MapboxMap.OnMapLongClickListener, ProgressChangeListener, MilestoneEventListener, OffRouteListener {
private static final int FIRST = 0;
private static final int ONE_HUNDRED_MILLISECONDS = 100;
@@ -80,7 +82,8 @@ public class ComponentNavigationActivity extends HistoryActivity implements OnMa
private static final double DEFAULT_ZOOM = 12.0;
private static final double DEFAULT_TILT = 0d;
private static final double DEFAULT_BEARING = 0d;
- private static final int ONE_SECOND_INTERVAL = 1000;
+ private static final long UPDATE_INTERVAL_IN_MILLISECONDS = 1000;
+ private static final long FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS = 500;
@BindView(R.id.componentNavigationLayout)
ConstraintLayout navigationLayout;
@@ -97,6 +100,7 @@ public class ComponentNavigationActivity extends HistoryActivity implements OnMa
@BindView(R.id.cancelNavigationFab)
FloatingActionButton cancelNavigationFab;
+ private final ComponentActivityLocationCallback callback = new ComponentActivityLocationCallback(this);
private LocationEngine locationEngine;
private MapboxNavigation navigation;
private NavigationSpeechPlayer speechPlayer;
@@ -125,26 +129,28 @@ protected void onCreate(Bundle savedInstanceState) {
}
@Override
- public void onMapReady(MapboxMap mapboxMap) {
- mapState = MapState.INFO;
- navigationMap = new NavigationMapboxMap(mapView, mapboxMap);
+ public void onMapReady(@NonNull MapboxMap mapboxMap) {
+ mapboxMap.setStyle(new Style.Builder().fromUrl(getString(R.string.navigation_guidance_day)), style -> {
+ mapState = MapState.INFO;
+ navigationMap = new NavigationMapboxMap(mapView, mapboxMap);
- // For Location updates
- initializeLocationEngine();
+ // For Location updates
+ initializeLocationEngine();
- // For navigation logic / processing
- initializeNavigation(mapboxMap);
- navigationMap.updateCameraTrackingMode(NavigationCamera.NAVIGATION_TRACKING_MODE_NONE);
+ // For navigation logic / processing
+ initializeNavigation(mapboxMap);
+ navigationMap.updateCameraTrackingMode(NavigationCamera.NAVIGATION_TRACKING_MODE_NONE);
- // For voice instructions
- initializeSpeechPlayer();
+ // For voice instructions
+ initializeSpeechPlayer();
+ });
}
@Override
- public void onMapLongClick(@NonNull LatLng point) {
+ public boolean onMapLongClick(@NonNull LatLng point) {
// Only reverse geocode while we are not in navigation
if (mapState.equals(MapState.NAVIGATION)) {
- return;
+ return true;
}
// Fetch the route with this given point
@@ -158,6 +164,7 @@ public void onMapLongClick(@NonNull LatLng point) {
// Update camera to new destination
moveCameraToInclude(destination);
vibrate();
+ return true;
}
@OnClick(R.id.startNavigationFab)
@@ -200,31 +207,6 @@ public void onCancelNavigationClick(FloatingActionButton floatingActionButton) {
addLocationEngineListener();
}
- /*
- * LocationEngine listeners
- */
-
- @SuppressLint("MissingPermission")
- @Override
- public void onConnected() {
- locationEngine.requestLocationUpdates();
- }
-
- @Override
- public void onLocationChanged(Location location) {
- if (lastLocation == null) {
- // Move the navigationMap camera to the first Location
- moveCameraTo(location);
-
- // Allow navigationMap clicks now that we have the current Location
- navigationMap.retrieveMap().addOnMapLongClickListener(this);
- showSnackbar(LONG_PRESS_MAP_MESSAGE, BaseTransientBottomBar.LENGTH_LONG);
- }
-
- // Cache for fetching the route later
- updateLocation(location);
- }
-
/*
* Navigation listeners
*/
@@ -315,6 +297,20 @@ protected void onDestroy() {
navigation.onDestroy();
}
+ void checkFirstUpdate(Location location) {
+ if (lastLocation == null) {
+ moveCameraTo(location);
+ // Allow navigationMap clicks now that we have the current Location
+ navigationMap.retrieveMap().addOnMapLongClickListener(this);
+ showSnackbar(LONG_PRESS_MAP_MESSAGE, BaseTransientBottomBar.LENGTH_LONG);
+ }
+ }
+
+ void updateLocation(Location location) {
+ lastLocation = location;
+ navigationMap.updateLocation(location);
+ }
+
private void initializeSpeechPlayer() {
String english = Locale.US.getLanguage();
Cache cache = new Cache(new File(getApplication().getCacheDir(), COMPONENT_NAVIGATION_INSTRUCTION_CACHE),
@@ -326,13 +322,11 @@ private void initializeSpeechPlayer() {
speechPlayer = new NavigationSpeechPlayer(speechPlayerProvider);
}
+ @SuppressLint("MissingPermission")
private void initializeLocationEngine() {
- locationEngine = new FusedLocationEngine(getApplicationContext());
- locationEngine.setPriority(LocationEnginePriority.HIGH_ACCURACY);
- locationEngine.addLocationEngineListener(this);
- locationEngine.setInterval(ONE_SECOND_INTERVAL);
- locationEngine.setFastestInterval(500);
- locationEngine.activate();
+ locationEngine = LocationEngineProvider.getBestLocationEngine(getApplicationContext());
+ LocationEngineRequest request = buildEngineRequest();
+ locationEngine.requestLocationUpdates(request, callback, null);
showSnackbar(SEARCHING_FOR_GPS_MESSAGE, BaseTransientBottomBar.LENGTH_SHORT);
}
@@ -360,11 +354,6 @@ private void playAnnouncement(Milestone milestone) {
}
}
- private void updateLocation(Location location) {
- lastLocation = location;
- navigationMap.updateLocation(location);
- }
-
private void moveCameraTo(Location location) {
CameraPosition cameraPosition = buildCameraPositionFrom(location, location.getBearing());
navigationMap.retrieveMap().animateCamera(
@@ -424,13 +413,15 @@ private void resetMapAfterNavigation() {
private void removeLocationEngineListener() {
if (locationEngine != null) {
- locationEngine.removeLocationEngineListener(this);
+ locationEngine.removeLocationUpdates(callback);
}
}
+ @SuppressLint("MissingPermission")
private void addLocationEngineListener() {
if (locationEngine != null) {
- locationEngine.addLocationEngineListener(this);
+ LocationEngineRequest request = buildEngineRequest();
+ locationEngine.requestLocationUpdates(request, callback, null);
}
}
@@ -477,4 +468,43 @@ private void vibrate() {
vibrator.vibrate(ONE_HUNDRED_MILLISECONDS);
}
}
+
+ @NonNull
+ private LocationEngineRequest buildEngineRequest() {
+ return new LocationEngineRequest.Builder(UPDATE_INTERVAL_IN_MILLISECONDS)
+ .setPriority(LocationEngineRequest.PRIORITY_HIGH_ACCURACY)
+ .setFastestInterval(FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS)
+ .build();
+ }
+
+ /*
+ * LocationEngine callback
+ */
+
+ private static class ComponentActivityLocationCallback implements LocationEngineCallback {
+
+ private final WeakReference activityWeakReference;
+
+ ComponentActivityLocationCallback(ComponentNavigationActivity activity) {
+ this.activityWeakReference = new WeakReference<>(activity);
+ }
+
+ @Override
+ public void onSuccess(LocationEngineResult result) {
+ ComponentNavigationActivity activity = activityWeakReference.get();
+ if (activity != null) {
+ Location location = result.getLastLocation();
+ if (location == null) {
+ return;
+ }
+ activity.checkFirstUpdate(location);
+ activity.updateLocation(location);
+ }
+ }
+
+ @Override
+ public void onFailure(@NonNull Exception exception) {
+ Timber.e(exception);
+ }
+ }
}
diff --git a/app/src/main/java/com/mapbox/services/android/navigation/testapp/activity/navigationui/DualNavigationMapActivity.java b/app/src/main/java/com/mapbox/services/android/navigation/testapp/activity/navigationui/DualNavigationMapActivity.java
index 0a1f85e6df5..2b34a4ecfc6 100644
--- a/app/src/main/java/com/mapbox/services/android/navigation/testapp/activity/navigationui/DualNavigationMapActivity.java
+++ b/app/src/main/java/com/mapbox/services/android/navigation/testapp/activity/navigationui/DualNavigationMapActivity.java
@@ -1,5 +1,6 @@
package com.mapbox.services.android.navigation.testapp.activity.navigationui;
+import android.annotation.SuppressLint;
import android.location.Location;
import android.os.Bundle;
import android.support.annotation.NonNull;
@@ -13,13 +14,15 @@
import android.widget.ProgressBar;
import com.mapbox.android.core.location.LocationEngine;
-import com.mapbox.android.core.location.LocationEngineListener;
+import com.mapbox.android.core.location.LocationEngineCallback;
import com.mapbox.android.core.location.LocationEngineProvider;
+import com.mapbox.android.core.location.LocationEngineRequest;
+import com.mapbox.android.core.location.LocationEngineResult;
import com.mapbox.api.directions.v5.models.DirectionsResponse;
import com.mapbox.api.directions.v5.models.DirectionsRoute;
import com.mapbox.geojson.Point;
import com.mapbox.mapboxsdk.annotations.Marker;
-import com.mapbox.mapboxsdk.annotations.MarkerViewOptions;
+import com.mapbox.mapboxsdk.annotations.MarkerOptions;
import com.mapbox.mapboxsdk.camera.CameraUpdateFactory;
import com.mapbox.mapboxsdk.geometry.LatLng;
import com.mapbox.mapboxsdk.location.LocationComponent;
@@ -27,6 +30,7 @@
import com.mapbox.mapboxsdk.maps.MapView;
import com.mapbox.mapboxsdk.maps.MapboxMap;
import com.mapbox.mapboxsdk.maps.OnMapReadyCallback;
+import com.mapbox.mapboxsdk.maps.Style;
import com.mapbox.services.android.navigation.testapp.R;
import com.mapbox.services.android.navigation.ui.v5.NavigationView;
import com.mapbox.services.android.navigation.ui.v5.NavigationViewOptions;
@@ -36,18 +40,22 @@
import com.mapbox.services.android.navigation.ui.v5.route.OnRouteSelectionChangeListener;
import com.mapbox.services.android.navigation.v5.navigation.NavigationRoute;
+import java.lang.ref.WeakReference;
+
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
-
-import static com.mapbox.android.core.location.LocationEnginePriority.HIGH_ACCURACY;
+import timber.log.Timber;
public class DualNavigationMapActivity extends AppCompatActivity implements OnNavigationReadyCallback,
NavigationListener, Callback, OnMapReadyCallback, MapboxMap.OnMapLongClickListener,
- LocationEngineListener, OnRouteSelectionChangeListener {
+ OnRouteSelectionChangeListener {
private static final int CAMERA_ANIMATION_DURATION = 1000;
private static final int DEFAULT_CAMERA_ZOOM = 16;
+ private static final long UPDATE_INTERVAL_IN_MILLISECONDS = 1000;
+ private static final long FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS = 500;
+ private final DualNavigationLocationCallback callback = new DualNavigationLocationCallback(this);
private ConstraintLayout dualNavigationMap;
private NavigationView navigationView;
private MapView mapView;
@@ -90,23 +98,26 @@ public void onNavigationReady(boolean isRunning) {
}
@Override
- public void onMapReady(MapboxMap mapboxMap) {
+ public void onMapReady(@NonNull MapboxMap mapboxMap) {
this.mapboxMap = mapboxMap;
this.mapboxMap.addOnMapLongClickListener(this);
- initLocationEngine();
- initializeLocationLayer();
- initMapRoute();
- fetchRoute();
+ mapboxMap.setStyle(Style.MAPBOX_STREETS, style -> {
+ initializeLocationEngine();
+ initializeLocationComponent(style);
+ initMapRoute();
+ fetchRoute();
+ });
}
@Override
- public void onMapLongClick(@NonNull LatLng point) {
+ public boolean onMapLongClick(@NonNull LatLng point) {
destination = Point.fromLngLat(point.getLongitude(), point.getLatitude());
updateLoadingTo(true);
setCurrentMarkerPosition(point);
if (origin != null) {
fetchRoute();
}
+ return true;
}
@Override
@@ -140,18 +151,6 @@ public void onNavigationFinished() {
public void onNavigationRunning() {
}
- @SuppressWarnings( {"MissingPermission"})
- @Override
- public void onConnected() {
- locationEngine.requestLocationUpdates();
- }
-
- @Override
- public void onLocationChanged(Location location) {
- origin = Point.fromLngLat(location.getLongitude(), location.getLatitude());
- onLocationFound(location);
- }
-
@Override
public void onNewPrimaryRouteSelected(DirectionsRoute directionsRoute) {
route = directionsRoute;
@@ -164,16 +163,15 @@ public void onStart() {
mapView.onStart();
}
+ @SuppressLint("MissingPermission")
@Override
public void onResume() {
super.onResume();
navigationView.onResume();
mapView.onResume();
if (locationEngine != null) {
- locationEngine.addLocationEngineListener(this);
- if (!locationEngine.isConnected()) {
- locationEngine.activate();
- }
+ LocationEngineRequest request = buildEngineRequest();
+ locationEngine.requestLocationUpdates(request, callback, null);
}
}
@@ -210,7 +208,7 @@ public void onPause() {
navigationView.onPause();
mapView.onPause();
if (locationEngine != null) {
- locationEngine.removeLocationEngineListener(this);
+ locationEngine.removeLocationUpdates(callback);
}
}
@@ -226,9 +224,14 @@ protected void onDestroy() {
super.onDestroy();
navigationView.onDestroy();
mapView.onDestroy();
- if (locationEngine != null) {
- locationEngine.removeLocationUpdates();
- locationEngine.deactivate();
+ }
+
+ void onLocationFound(Location location) {
+ origin = Point.fromLngLat(location.getLongitude(), location.getLatitude());
+ if (!locationFound) {
+ animateCamera(new LatLng(location.getLatitude(), location.getLongitude()));
+ locationFound = true;
+ updateLoadingTo(false);
}
}
@@ -287,27 +290,24 @@ private boolean validRouteResponse(Response response) {
return response.body() != null && !response.body().routes().isEmpty();
}
+ @SuppressWarnings("MissingPermission")
+ private void initializeLocationEngine() {
+ locationEngine = LocationEngineProvider.getBestLocationEngine(getApplicationContext());
+ locationEngine.getLastLocation(callback);
+ }
- @SuppressWarnings( {"MissingPermission"})
- private void initLocationEngine() {
- locationEngine = new LocationEngineProvider(this).obtainBestLocationEngineAvailable();
- locationEngine.setPriority(HIGH_ACCURACY);
- locationEngine.setInterval(0);
- locationEngine.setFastestInterval(1000);
- locationEngine.addLocationEngineListener(this);
- locationEngine.activate();
-
- if (locationEngine.getLastLocation() != null) {
- Location lastLocation = locationEngine.getLastLocation();
- onLocationChanged(lastLocation);
- origin = Point.fromLngLat(lastLocation.getLongitude(), lastLocation.getLatitude());
- }
+ @NonNull
+ private LocationEngineRequest buildEngineRequest() {
+ return new LocationEngineRequest.Builder(UPDATE_INTERVAL_IN_MILLISECONDS)
+ .setPriority(LocationEngineRequest.PRIORITY_HIGH_ACCURACY)
+ .setFastestInterval(FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS)
+ .build();
}
- @SuppressWarnings( {"MissingPermission"})
- private void initializeLocationLayer() {
+ @SuppressLint("MissingPermission")
+ private void initializeLocationComponent(Style style) {
LocationComponent locationComponent = mapboxMap.getLocationComponent();
- locationComponent.activateLocationComponent(this, locationEngine);
+ locationComponent.activateLocationComponent(this, style, locationEngine);
locationComponent.setLocationComponentEnabled(true);
locationComponent.setRenderMode(RenderMode.COMPASS);
}
@@ -320,7 +320,7 @@ private void initMapRoute() {
private void setCurrentMarkerPosition(LatLng position) {
if (position != null) {
if (currentMarker == null) {
- MarkerViewOptions markerViewOptions = new MarkerViewOptions()
+ MarkerOptions markerViewOptions = new MarkerOptions()
.position(position);
currentMarker = mapboxMap.addMarker(markerViewOptions);
} else {
@@ -329,15 +329,33 @@ private void setCurrentMarkerPosition(LatLng position) {
}
}
- private void onLocationFound(Location location) {
- if (!locationFound) {
- animateCamera(new LatLng(location.getLatitude(), location.getLongitude()));
- locationFound = true;
- updateLoadingTo(false);
- }
- }
-
private void animateCamera(LatLng point) {
mapboxMap.animateCamera(CameraUpdateFactory.newLatLngZoom(point, DEFAULT_CAMERA_ZOOM), CAMERA_ANIMATION_DURATION);
}
+
+ private static class DualNavigationLocationCallback implements LocationEngineCallback {
+
+ private final WeakReference activityWeakReference;
+
+ DualNavigationLocationCallback(DualNavigationMapActivity activity) {
+ this.activityWeakReference = new WeakReference<>(activity);
+ }
+
+ @Override
+ public void onSuccess(LocationEngineResult result) {
+ DualNavigationMapActivity activity = activityWeakReference.get();
+ if (activity != null) {
+ Location location = result.getLastLocation();
+ if (location == null) {
+ return;
+ }
+ activity.onLocationFound(location);
+ }
+ }
+
+ @Override
+ public void onFailure(@NonNull Exception exception) {
+ Timber.e(exception);
+ }
+ }
}
\ No newline at end of file
diff --git a/app/src/main/java/com/mapbox/services/android/navigation/testapp/activity/navigationui/NavigationLauncherActivity.java b/app/src/main/java/com/mapbox/services/android/navigation/testapp/activity/navigationui/NavigationLauncherActivity.java
index 5c770e3ef37..549e68b06cf 100644
--- a/app/src/main/java/com/mapbox/services/android/navigation/testapp/activity/navigationui/NavigationLauncherActivity.java
+++ b/app/src/main/java/com/mapbox/services/android/navigation/testapp/activity/navigationui/NavigationLauncherActivity.java
@@ -18,8 +18,10 @@
import android.widget.Toast;
import com.mapbox.android.core.location.LocationEngine;
-import com.mapbox.android.core.location.LocationEngineListener;
+import com.mapbox.android.core.location.LocationEngineCallback;
import com.mapbox.android.core.location.LocationEngineProvider;
+import com.mapbox.android.core.location.LocationEngineRequest;
+import com.mapbox.android.core.location.LocationEngineResult;
import com.mapbox.api.directions.v5.DirectionsCriteria;
import com.mapbox.api.directions.v5.models.DirectionsResponse;
import com.mapbox.api.directions.v5.models.DirectionsRoute;
@@ -28,7 +30,7 @@
import com.mapbox.geojson.Point;
import com.mapbox.mapboxsdk.Mapbox;
import com.mapbox.mapboxsdk.annotations.Marker;
-import com.mapbox.mapboxsdk.annotations.MarkerViewOptions;
+import com.mapbox.mapboxsdk.annotations.MarkerOptions;
import com.mapbox.mapboxsdk.camera.CameraPosition;
import com.mapbox.mapboxsdk.camera.CameraUpdateFactory;
import com.mapbox.mapboxsdk.exceptions.InvalidLatLngBoundsException;
@@ -39,6 +41,7 @@
import com.mapbox.mapboxsdk.maps.MapView;
import com.mapbox.mapboxsdk.maps.MapboxMap;
import com.mapbox.mapboxsdk.maps.OnMapReadyCallback;
+import com.mapbox.mapboxsdk.maps.Style;
import com.mapbox.services.android.navigation.testapp.NavigationSettingsActivity;
import com.mapbox.services.android.navigation.testapp.R;
import com.mapbox.services.android.navigation.ui.v5.NavigationLauncher;
@@ -48,6 +51,7 @@
import com.mapbox.services.android.navigation.v5.navigation.NavigationRoute;
import com.mapbox.services.android.navigation.v5.utils.LocaleUtils;
+import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
@@ -57,17 +61,19 @@
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Response;
-
-import static com.mapbox.android.core.location.LocationEnginePriority.HIGH_ACCURACY;
+import timber.log.Timber;
public class NavigationLauncherActivity extends AppCompatActivity implements OnMapReadyCallback,
- MapboxMap.OnMapLongClickListener, LocationEngineListener, OnRouteSelectionChangeListener {
+ MapboxMap.OnMapLongClickListener, OnRouteSelectionChangeListener {
private static final int CAMERA_ANIMATION_DURATION = 1000;
private static final int DEFAULT_CAMERA_ZOOM = 16;
private static final int CHANGE_SETTING_REQUEST_CODE = 1;
private static final int INITIAL_ZOOM = 16;
+ private static final long UPDATE_INTERVAL_IN_MILLISECONDS = 1000;
+ private static final long FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS = 500;
+ private final NavigationLauncherLocationCallback callback = new NavigationLauncherLocationCallback(this);
private LocationEngine locationEngine;
private NavigationMapRoute mapRoute;
private MapboxMap mapboxMap;
@@ -115,10 +121,6 @@ public boolean onOptionsItemSelected(MenuItem item) {
}
}
- private void showSettings() {
- startActivityForResult(new Intent(this, NavigationSettingsActivity.class), CHANGE_SETTING_REQUEST_CODE);
- }
-
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
@@ -143,10 +145,7 @@ public void onResume() {
super.onResume();
mapView.onResume();
if (locationEngine != null) {
- locationEngine.addLocationEngineListener(this);
- if (!locationEngine.isConnected()) {
- locationEngine.activate();
- }
+ locationEngine.requestLocationUpdates(buildEngineRequest(), callback, null);
}
}
@@ -155,7 +154,7 @@ public void onPause() {
super.onPause();
mapView.onPause();
if (locationEngine != null) {
- locationEngine.removeLocationEngineListener(this);
+ locationEngine.removeLocationUpdates(callback);
}
}
@@ -175,10 +174,6 @@ protected void onStop() {
protected void onDestroy() {
super.onDestroy();
mapView.onDestroy();
- if (locationEngine != null) {
- locationEngine.removeLocationUpdates();
- locationEngine.deactivate();
- }
}
@Override
@@ -195,14 +190,16 @@ public void onRouteLaunchClick() {
@Override
public void onMapReady(MapboxMap mapboxMap) {
this.mapboxMap = mapboxMap;
- this.mapboxMap.addOnMapLongClickListener(this);
- initLocationEngine();
- initializeLocationComponent();
- initMapRoute();
+ mapboxMap.setStyle(Style.MAPBOX_STREETS, style -> {
+ mapboxMap.addOnMapLongClickListener(this);
+ initializeLocationEngine();
+ initializeLocationComponent(style);
+ initializeMapRoute();
+ });
}
@Override
- public void onMapLongClick(@NonNull LatLng point) {
+ public boolean onMapLongClick(@NonNull LatLng point) {
destination = Point.fromLngLat(point.getLongitude(), point.getLatitude());
launchRouteBtn.setEnabled(false);
loading.setVisibility(View.VISIBLE);
@@ -210,50 +207,48 @@ public void onMapLongClick(@NonNull LatLng point) {
if (currentLocation != null) {
fetchRoute();
}
+ return true;
}
- @SuppressWarnings( {"MissingPermission"})
@Override
- public void onConnected() {
- locationEngine.requestLocationUpdates();
+ public void onNewPrimaryRouteSelected(DirectionsRoute directionsRoute) {
+ route = directionsRoute;
}
- @Override
- public void onLocationChanged(Location location) {
- currentLocation = Point.fromLngLat(location.getLongitude(), location.getLatitude());
- onLocationFound(location);
+ void updateCurrentLocation(Point currentLocation) {
+ this.currentLocation = currentLocation;
}
- @Override
- public void onNewPrimaryRouteSelected(DirectionsRoute directionsRoute) {
- route = directionsRoute;
+ void onLocationFound(Location location) {
+ if (!locationFound) {
+ animateCamera(new LatLng(location.getLatitude(), location.getLongitude()));
+ Snackbar.make(mapView, R.string.explanation_long_press_waypoint, Snackbar.LENGTH_LONG).show();
+ locationFound = true;
+ hideLoading();
+ }
+ }
+
+ private void showSettings() {
+ startActivityForResult(new Intent(this, NavigationSettingsActivity.class), CHANGE_SETTING_REQUEST_CODE);
}
@SuppressWarnings( {"MissingPermission"})
- private void initLocationEngine() {
- locationEngine = new LocationEngineProvider(this).obtainBestLocationEngineAvailable();
- locationEngine.setPriority(HIGH_ACCURACY);
- locationEngine.setInterval(0);
- locationEngine.setFastestInterval(1000);
- locationEngine.addLocationEngineListener(this);
- locationEngine.activate();
-
- if (locationEngine.getLastLocation() != null) {
- Location lastLocation = locationEngine.getLastLocation();
- onLocationChanged(lastLocation);
- currentLocation = Point.fromLngLat(lastLocation.getLongitude(), lastLocation.getLatitude());
- }
+ private void initializeLocationEngine() {
+ locationEngine = LocationEngineProvider.getBestLocationEngine(getApplicationContext());
+ LocationEngineRequest request = buildEngineRequest();
+ locationEngine.requestLocationUpdates(request, callback, null);
+ locationEngine.getLastLocation(callback);
}
@SuppressWarnings( {"MissingPermission"})
- private void initializeLocationComponent() {
+ private void initializeLocationComponent(Style style) {
LocationComponent locationComponent = mapboxMap.getLocationComponent();
- locationComponent.activateLocationComponent(this, locationEngine);
+ locationComponent.activateLocationComponent(this, style, locationEngine);
locationComponent.setLocationComponentEnabled(true);
locationComponent.setRenderMode(RenderMode.COMPASS);
}
- private void initMapRoute() {
+ private void initializeMapRoute() {
mapRoute = new NavigationMapRoute(mapView, mapboxMap);
mapRoute.setOnRouteSelectionChangeListener(this);
}
@@ -353,15 +348,6 @@ private void hideLoading() {
}
}
- private void onLocationFound(Location location) {
- if (!locationFound) {
- animateCamera(new LatLng(location.getLatitude(), location.getLongitude()));
- Snackbar.make(mapView, R.string.explanation_long_press_waypoint, Snackbar.LENGTH_LONG).show();
- locationFound = true;
- hideLoading();
- }
- }
-
public void boundCameraToRoute() {
if (route != null) {
List routeCoords = LineString.fromPolyline(route.geometry(),
@@ -395,7 +381,7 @@ private void animateCamera(LatLng point) {
private void setCurrentMarkerPosition(LatLng position) {
if (position != null) {
if (currentMarker == null) {
- MarkerViewOptions markerViewOptions = new MarkerViewOptions()
+ MarkerOptions markerViewOptions = new MarkerOptions()
.position(position);
currentMarker = mapboxMap.addMarker(markerViewOptions);
} else {
@@ -403,4 +389,39 @@ private void setCurrentMarkerPosition(LatLng position) {
}
}
}
+
+ @NonNull
+ private LocationEngineRequest buildEngineRequest() {
+ return new LocationEngineRequest.Builder(UPDATE_INTERVAL_IN_MILLISECONDS)
+ .setPriority(LocationEngineRequest.PRIORITY_HIGH_ACCURACY)
+ .setFastestInterval(FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS)
+ .build();
+ }
+
+ private static class NavigationLauncherLocationCallback implements LocationEngineCallback {
+
+ private final WeakReference activityWeakReference;
+
+ NavigationLauncherLocationCallback(NavigationLauncherActivity activity) {
+ this.activityWeakReference = new WeakReference<>(activity);
+ }
+
+ @Override
+ public void onSuccess(LocationEngineResult result) {
+ NavigationLauncherActivity activity = activityWeakReference.get();
+ if (activity != null) {
+ Location location = result.getLastLocation();
+ if (location == null) {
+ return;
+ }
+ activity.updateCurrentLocation(Point.fromLngLat(location.getLongitude(), location.getLatitude()));
+ activity.onLocationFound(location);
+ }
+ }
+
+ @Override
+ public void onFailure(@NonNull Exception exception) {
+ Timber.e(exception);
+ }
+ }
}
diff --git a/app/src/main/java/com/mapbox/services/android/navigation/testapp/activity/navigationui/NavigationMapRouteActivity.java b/app/src/main/java/com/mapbox/services/android/navigation/testapp/activity/navigationui/NavigationMapRouteActivity.java
index 4378394814d..6e42bcbe77a 100644
--- a/app/src/main/java/com/mapbox/services/android/navigation/testapp/activity/navigationui/NavigationMapRouteActivity.java
+++ b/app/src/main/java/com/mapbox/services/android/navigation/testapp/activity/navigationui/NavigationMapRouteActivity.java
@@ -19,7 +19,6 @@
import com.mapbox.mapboxsdk.Mapbox;
import com.mapbox.mapboxsdk.annotations.Marker;
import com.mapbox.mapboxsdk.annotations.MarkerOptions;
-import com.mapbox.mapboxsdk.constants.Style;
import com.mapbox.mapboxsdk.geometry.LatLng;
import com.mapbox.mapboxsdk.location.LocationComponent;
import com.mapbox.mapboxsdk.location.modes.CameraMode;
@@ -27,6 +26,7 @@
import com.mapbox.mapboxsdk.maps.MapView;
import com.mapbox.mapboxsdk.maps.MapboxMap;
import com.mapbox.mapboxsdk.maps.OnMapReadyCallback;
+import com.mapbox.mapboxsdk.maps.Style;
import com.mapbox.services.android.navigation.testapp.R;
import com.mapbox.services.android.navigation.ui.v5.route.NavigationMapRoute;
import com.mapbox.services.android.navigation.v5.navigation.NavigationRoute;
@@ -66,7 +66,6 @@ protected void onCreate(Bundle savedInstanceState) {
setContentView(R.layout.activity_navigation_map_route);
ButterKnife.bind(this);
- mapView.setStyleUrl(styleCycle.getStyle());
mapView.onCreate(savedInstanceState);
mapView.getMapAsync(this);
}
@@ -74,7 +73,7 @@ protected void onCreate(Bundle savedInstanceState) {
@OnClick(R.id.fabStyles)
public void onStyleFabClick() {
if (mapboxMap != null) {
- mapboxMap.setStyleUrl(styleCycle.getNextStyle());
+ mapboxMap.setStyle(styleCycle.getNextStyle());
}
}
@@ -87,15 +86,18 @@ public void onRemoveRouteClick(View fabRemoveRoute) {
@Override
public void onMapReady(MapboxMap mapboxMap) {
this.mapboxMap = mapboxMap;
- initializeLocationComponent(mapboxMap);
- navigationMapRoute = new NavigationMapRoute(null, mapView, mapboxMap);
- mapboxMap.addOnMapLongClickListener(this);
- Snackbar.make(mapView, "Long press to select route", Snackbar.LENGTH_SHORT).show();
+ mapboxMap.setStyle(styleCycle.getStyle(), style -> {
+ initializeLocationComponent(mapboxMap);
+ navigationMapRoute = new NavigationMapRoute(null, mapView, mapboxMap);
+ mapboxMap.addOnMapLongClickListener(this);
+ Snackbar.make(mapView, "Long press to select route", Snackbar.LENGTH_SHORT).show();
+ });
}
@Override
- public void onMapLongClick(@NonNull LatLng point) {
+ public boolean onMapLongClick(@NonNull LatLng point) {
handleClicked(point);
+ return true;
}
@Override
@@ -166,7 +168,7 @@ protected void onSaveInstanceState(Bundle outState) {
@SuppressWarnings("MissingPermission")
private void initializeLocationComponent(MapboxMap mapboxMap) {
LocationComponent locationComponent = mapboxMap.getLocationComponent();
- locationComponent.activateLocationComponent(this);
+ locationComponent.activateLocationComponent(this, mapboxMap.getStyle());
locationComponent.setLocationComponentEnabled(true);
locationComponent.setRenderMode(RenderMode.COMPASS);
locationComponent.setCameraMode(CameraMode.TRACKING);
diff --git a/app/src/main/java/com/mapbox/services/android/navigation/testapp/example/ui/ExampleActivity.kt b/app/src/main/java/com/mapbox/services/android/navigation/testapp/example/ui/ExampleActivity.kt
index 6191c157ce2..db1904290ad 100644
--- a/app/src/main/java/com/mapbox/services/android/navigation/testapp/example/ui/ExampleActivity.kt
+++ b/app/src/main/java/com/mapbox/services/android/navigation/testapp/example/ui/ExampleActivity.kt
@@ -20,6 +20,7 @@ import com.mapbox.mapboxsdk.geometry.LatLngBounds
import com.mapbox.mapboxsdk.location.modes.RenderMode
import com.mapbox.mapboxsdk.maps.AttributionDialogManager
import com.mapbox.mapboxsdk.maps.MapboxMap
+import com.mapbox.mapboxsdk.maps.Style
import com.mapbox.services.android.navigation.testapp.NavigationSettingsActivity
import com.mapbox.services.android.navigation.testapp.R
import com.mapbox.services.android.navigation.testapp.activity.HistoryActivity
@@ -109,12 +110,14 @@ class ExampleActivity : HistoryActivity(), ExampleView {
}
override fun onMapReady(mapboxMap: MapboxMap) {
- map = NavigationMapboxMap(mapView, mapboxMap)
- map?.setOnRouteSelectionChangeListener(this)
- map?.updateLocationLayerRenderMode(RenderMode.NORMAL)
- mapboxMap.addOnMapLongClickListener { presenter.onMapLongClick(it) }
- presenter.buildDynamicCameraFrom(mapboxMap)
- resetMapPadding() // Ignore navigation padding default
+ mapboxMap.setStyle(Style.Builder().fromUrl(getString(R.string.navigation_guidance_day))) {
+ map = NavigationMapboxMap(mapView, mapboxMap)
+ map?.setOnRouteSelectionChangeListener(this)
+ map?.updateLocationLayerRenderMode(RenderMode.NORMAL)
+ mapboxMap.addOnMapLongClickListener { point -> presenter.onMapLongClick(point) }
+ presenter.buildDynamicCameraFrom(mapboxMap)
+ resetMapPadding() // Ignore navigation padding default
+ }
}
override fun onFeatureClicked(feature: CarmenFeature) {
@@ -151,9 +154,11 @@ class ExampleActivity : HistoryActivity(), ExampleView {
}
override fun updateMapCameraFor(bounds: LatLngBounds, padding: IntArray, duration: Int) {
- map?.retrieveMap()?.let {
- val position = it.getCameraForLatLngBounds(bounds, padding)
- it.animateCamera(CameraUpdateFactory.newCameraPosition(position), duration)
+ map?.retrieveMap()?.let { map ->
+ val position = map.getCameraForLatLngBounds(bounds, padding)
+ position?.let {
+ map.animateCamera(CameraUpdateFactory.newCameraPosition(it), duration)
+ }
}
}
diff --git a/app/src/main/java/com/mapbox/services/android/navigation/testapp/example/ui/ExampleLocationEngineCallback.kt b/app/src/main/java/com/mapbox/services/android/navigation/testapp/example/ui/ExampleLocationEngineCallback.kt
new file mode 100644
index 00000000000..0ba565c5def
--- /dev/null
+++ b/app/src/main/java/com/mapbox/services/android/navigation/testapp/example/ui/ExampleLocationEngineCallback.kt
@@ -0,0 +1,19 @@
+package com.mapbox.services.android.navigation.testapp.example.ui
+
+import android.arch.lifecycle.MutableLiveData
+import android.location.Location
+import com.mapbox.android.core.location.LocationEngineCallback
+import com.mapbox.android.core.location.LocationEngineResult
+import timber.log.Timber
+
+class ExampleLocationEngineCallback(private val location: MutableLiveData):
+ LocationEngineCallback {
+
+ override fun onSuccess(result: LocationEngineResult) {
+ location.value = result.lastLocation
+ }
+
+ override fun onFailure(exception: Exception) {
+ Timber.e(exception)
+ }
+}
\ No newline at end of file
diff --git a/app/src/main/java/com/mapbox/services/android/navigation/testapp/example/ui/ExamplePresenter.kt b/app/src/main/java/com/mapbox/services/android/navigation/testapp/example/ui/ExamplePresenter.kt
index 1432f6ad1f4..ccd2e31d9aa 100644
--- a/app/src/main/java/com/mapbox/services/android/navigation/testapp/example/ui/ExamplePresenter.kt
+++ b/app/src/main/java/com/mapbox/services/android/navigation/testapp/example/ui/ExamplePresenter.kt
@@ -197,8 +197,9 @@ class ExamplePresenter(private val view: ExampleView, private val viewModel: Exa
}
}
- fun onMapLongClick(point: LatLng) {
+ fun onMapLongClick(point: LatLng): Boolean {
viewModel.reverseGeocode(point)
+ return true
}
fun onBackPressed(): Boolean {
diff --git a/app/src/main/java/com/mapbox/services/android/navigation/testapp/example/ui/ExampleViewModel.kt b/app/src/main/java/com/mapbox/services/android/navigation/testapp/example/ui/ExampleViewModel.kt
index 64289a05762..1cb02ce0daf 100644
--- a/app/src/main/java/com/mapbox/services/android/navigation/testapp/example/ui/ExampleViewModel.kt
+++ b/app/src/main/java/com/mapbox/services/android/navigation/testapp/example/ui/ExampleViewModel.kt
@@ -1,12 +1,14 @@
package com.mapbox.services.android.navigation.testapp.example.ui
+import android.annotation.SuppressLint
import android.app.Application
import android.arch.lifecycle.AndroidViewModel
import android.arch.lifecycle.MutableLiveData
import android.location.Location
import android.preference.PreferenceManager
import com.mapbox.android.core.location.LocationEngine
-import com.mapbox.android.core.location.LocationEnginePriority
+import com.mapbox.android.core.location.LocationEngineProvider
+import com.mapbox.android.core.location.LocationEngineRequest
import com.mapbox.api.directions.v5.models.DirectionsRoute
import com.mapbox.api.geocoding.v5.GeocodingCriteria
import com.mapbox.api.geocoding.v5.MapboxGeocoding
@@ -16,8 +18,10 @@ import com.mapbox.mapboxsdk.Mapbox
import com.mapbox.mapboxsdk.geometry.LatLng
import com.mapbox.services.android.navigation.testapp.NavigationApplication.Companion.instance
import com.mapbox.services.android.navigation.testapp.R
-import com.mapbox.services.android.navigation.testapp.activity.location.FusedLocationEngine
-import com.mapbox.services.android.navigation.testapp.example.ui.navigation.*
+import com.mapbox.services.android.navigation.testapp.example.ui.navigation.ExampleMilestoneEventListener
+import com.mapbox.services.android.navigation.testapp.example.ui.navigation.ExampleOffRouteListener
+import com.mapbox.services.android.navigation.testapp.example.ui.navigation.ExampleProgressChangeListener
+import com.mapbox.services.android.navigation.testapp.example.ui.navigation.RouteFinder
import com.mapbox.services.android.navigation.ui.v5.camera.DynamicCamera
import com.mapbox.services.android.navigation.ui.v5.voice.NavigationSpeechPlayer
import com.mapbox.services.android.navigation.ui.v5.voice.SpeechPlayerProvider
@@ -33,7 +37,8 @@ import timber.log.Timber
import java.io.File
import java.util.Locale.US
-private const val ONE_SECOND_INTERVAL = 1000
+private const val UPDATE_INTERVAL_IN_MILLISECONDS: Long = 1000
+private const val FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS: Long = 500
private const val EXAMPLE_INSTRUCTION_CACHE = "example-navigation-instruction-cache"
private const val TEN_MEGABYTE_CACHE_SIZE: Long = 10 * 1024 * 1024
@@ -51,7 +56,7 @@ class ExampleViewModel(application: Application) : AndroidViewModel(application)
var isOffRoute: Boolean = false
private val locationEngine: LocationEngine
- private val locationEngineListener: ExampleLocationEngineListener
+ private val locationEngineCallback: ExampleLocationEngineCallback
private val speechPlayer: NavigationSpeechPlayer
private val navigation: MapboxNavigation
@@ -61,11 +66,8 @@ class ExampleViewModel(application: Application) : AndroidViewModel(application)
init {
routeFinder = RouteFinder(this, routes, accessToken, retrieveOfflineVersionFromPreferences())
// Initialize the location engine
- locationEngine = FusedLocationEngine(getApplication())
- locationEngineListener = ExampleLocationEngineListener(locationEngine, location)
- locationEngine.addLocationEngineListener(locationEngineListener)
- locationEngine.priority = LocationEnginePriority.HIGH_ACCURACY
- locationEngine.fastestInterval = ONE_SECOND_INTERVAL
+ locationEngine = LocationEngineProvider.getBestLocationEngine(getApplication())
+ locationEngineCallback = ExampleLocationEngineCallback(location)
// Initialize navigation and pass the LocationEngine
navigation = MapboxNavigation(getApplication(), accessToken)
@@ -74,7 +76,7 @@ class ExampleViewModel(application: Application) : AndroidViewModel(application)
// Initialize the speech player and pass to milestone event listener for instructions
val english = US.language // TODO localization
val cache = Cache(File(application.cacheDir, EXAMPLE_INSTRUCTION_CACHE),
- TEN_MEGABYTE_CACHE_SIZE)
+ TEN_MEGABYTE_CACHE_SIZE)
val voiceInstructionLoader = VoiceInstructionLoader(getApplication(), accessToken, cache)
val speechPlayerProvider = SpeechPlayerProvider(getApplication(), english, true, voiceInstructionLoader)
speechPlayer = NavigationSpeechPlayer(speechPlayerProvider)
@@ -89,7 +91,7 @@ class ExampleViewModel(application: Application) : AndroidViewModel(application)
}
fun activateLocationEngine() {
- locationEngine.activate()
+ requestLocation()
}
fun findRouteToDestination() {
@@ -111,12 +113,12 @@ class ExampleViewModel(application: Application) : AndroidViewModel(application)
fun startNavigation() {
primaryRoute?.let {
navigation.startNavigation(it)
- removeLocationEngineListener()
+ removeLocation()
}
}
fun stopNavigation() {
- addLocationEngineListener()
+ requestLocation()
navigation.stopNavigation()
}
@@ -126,10 +128,10 @@ class ExampleViewModel(application: Application) : AndroidViewModel(application)
fun reverseGeocode(point: LatLng) {
val reverseGeocode = MapboxGeocoding.builder()
- .accessToken(Mapbox.getAccessToken()!!)
- .query(Point.fromLngLat(point.longitude, point.latitude))
- .geocodingTypes(GeocodingCriteria.TYPE_ADDRESS)
- .build()
+ .accessToken(Mapbox.getAccessToken()!!)
+ .query(Point.fromLngLat(point.longitude, point.latitude))
+ .geocodingTypes(GeocodingCriteria.TYPE_ADDRESS)
+ .build()
reverseGeocode.enqueueCall(object : Callback {
override fun onResponse(call: Call, response: Response) {
geocode.value = response.body()
@@ -153,20 +155,29 @@ class ExampleViewModel(application: Application) : AndroidViewModel(application)
}
navigation.onDestroy()
speechPlayer.onDestroy()
- removeLocationEngineListener()
+ removeLocation()
}
- private fun addLocationEngineListener() {
- locationEngine.addLocationEngineListener(locationEngineListener)
+ @SuppressLint("MissingPermission")
+ private fun requestLocation() {
+ val request = buildEngineRequest()
+ locationEngine.requestLocationUpdates(request, locationEngineCallback, null)
}
- private fun removeLocationEngineListener() {
- locationEngine.removeLocationEngineListener(locationEngineListener)
+ private fun removeLocation() {
+ locationEngine.removeLocationUpdates(locationEngineCallback)
}
private fun retrieveOfflineVersionFromPreferences(): String {
val context = getApplication()
return PreferenceManager.getDefaultSharedPreferences(context)
- .getString(context.getString(R.string.offline_version_key), "")
+ .getString(context.getString(R.string.offline_version_key), "")
+ }
+
+ private fun buildEngineRequest(): LocationEngineRequest {
+ return LocationEngineRequest.Builder(UPDATE_INTERVAL_IN_MILLISECONDS)
+ .setPriority(LocationEngineRequest.PRIORITY_HIGH_ACCURACY)
+ .setFastestInterval(FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS)
+ .build()
}
}
\ No newline at end of file
diff --git a/app/src/main/java/com/mapbox/services/android/navigation/testapp/example/ui/callout/ExampleCalloutManager.java b/app/src/main/java/com/mapbox/services/android/navigation/testapp/example/ui/callout/ExampleCalloutManager.java
index 997b32483e1..d1e4a84a8fa 100644
--- a/app/src/main/java/com/mapbox/services/android/navigation/testapp/example/ui/callout/ExampleCalloutManager.java
+++ b/app/src/main/java/com/mapbox/services/android/navigation/testapp/example/ui/callout/ExampleCalloutManager.java
@@ -45,8 +45,8 @@ public class ExampleCalloutManager {
public ExampleCalloutManager(MapboxMap mapboxMap) {
this.mapboxMap = mapboxMap;
this.geoJsonSource = new GeoJsonSource(SOURCE_ID);
- mapboxMap.addSource(geoJsonSource);
- mapboxMap.addLayer(new SymbolLayer(LAYER_ID, SOURCE_ID).withProperties(
+ mapboxMap.getStyle().addSource(geoJsonSource);
+ mapboxMap.getStyle().addLayer(new SymbolLayer(LAYER_ID, SOURCE_ID).withProperties(
iconImage(string(get(literal(ExampleCallout.KEY_ID)))),
iconAllowOverlap(true),
iconIgnorePlacement(true),
@@ -135,7 +135,7 @@ private Bitmap generateText(Context context, ExampleCallout callout) {
@Override
protected void onPostExecute(HashMap bitmapHashMap) {
super.onPostExecute(bitmapHashMap);
- mapboxMap.addImages(bitmapHashMap);
+ mapboxMap.getStyle().addImages(bitmapHashMap);
}
}
diff --git a/app/src/main/java/com/mapbox/services/android/navigation/testapp/example/ui/navigation/ExampleLocationEngineListener.kt b/app/src/main/java/com/mapbox/services/android/navigation/testapp/example/ui/navigation/ExampleLocationEngineListener.kt
deleted file mode 100644
index 152243395e3..00000000000
--- a/app/src/main/java/com/mapbox/services/android/navigation/testapp/example/ui/navigation/ExampleLocationEngineListener.kt
+++ /dev/null
@@ -1,24 +0,0 @@
-package com.mapbox.services.android.navigation.testapp.example.ui.navigation
-
-import android.annotation.SuppressLint
-import android.arch.lifecycle.MutableLiveData
-import android.location.Location
-import com.mapbox.android.core.location.LocationEngine
-import com.mapbox.android.core.location.LocationEngineListener
-
-class ExampleLocationEngineListener(private val locationEngine: LocationEngine,
- private val location: MutableLiveData): LocationEngineListener {
-
- override fun onLocationChanged(location: Location?) {
- this.location.value = location
- }
-
- @SuppressLint("MissingPermission")
- override fun onConnected() {
- locationEngine.requestLocationUpdates()
-
- if (locationEngine.lastLocation != null) {
- onLocationChanged(locationEngine.lastLocation)
- }
- }
-}
\ No newline at end of file
diff --git a/app/src/main/res/layout/activity_component_navigation.xml b/app/src/main/res/layout/activity_component_navigation.xml
index bd7f7f0e627..b45a775f525 100644
--- a/app/src/main/res/layout/activity_component_navigation.xml
+++ b/app/src/main/res/layout/activity_component_navigation.xml
@@ -2,7 +2,6 @@
@@ -14,8 +13,7 @@
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
- app:layout_constraintTop_toTopOf="parent"
- mapbox:mapbox_styleUrl="mapbox://styles/designevokes/cjksybfj600xj2roja7iwnygu"/>
+ app:layout_constraintTop_toTopOf="parent"/>
diff --git a/app/src/main/res/layout/activity_mock_navigation.xml b/app/src/main/res/layout/activity_mock_navigation.xml
index d81d5ff8edf..e54b36cd1d8 100644
--- a/app/src/main/res/layout/activity_mock_navigation.xml
+++ b/app/src/main/res/layout/activity_mock_navigation.xml
@@ -14,7 +14,6 @@
android:layout_width="match_parent"
android:layout_height="match_parent"
app:mapbox_cameraZoom="14"
- app:mapbox_styleUrl="@string/mapbox_style_mapbox_streets"
app:mapbox_uiAttribution="false"/>
layers = mapboxMap.getLayers();
+ List layers = mapboxMap.getStyle().getLayers();
updateLayerWithVisibility(layerIdentifier, layers, isVisible);
}
boolean isLayerVisible(String layerIdentifier) {
// TODO add sourceIdentifier logic when https://github.com/mapbox/mapbox-gl-native/issues/12691 lands
- List layers = mapboxMap.getLayers();
+ List layers = mapboxMap.getStyle().getLayers();
return findLayerVisibility(layerIdentifier, layers);
}
diff --git a/libandroid-navigation-ui/src/main/java/com/mapbox/services/android/navigation/ui/v5/map/NavigationMapboxMap.java b/libandroid-navigation-ui/src/main/java/com/mapbox/services/android/navigation/ui/v5/map/NavigationMapboxMap.java
index 93acb449b89..84fa3ad47a2 100644
--- a/libandroid-navigation-ui/src/main/java/com/mapbox/services/android/navigation/ui/v5/map/NavigationMapboxMap.java
+++ b/libandroid-navigation-ui/src/main/java/com/mapbox/services/android/navigation/ui/v5/map/NavigationMapboxMap.java
@@ -1,5 +1,6 @@
package com.mapbox.services.android.navigation.ui.v5.map;
+import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Color;
import android.graphics.PointF;
@@ -58,6 +59,7 @@ public class NavigationMapboxMap {
private static final String INCIDENTS_LAYER_ID = "closures";
private static final String TRAFFIC_LAYER_ID = "traffic";
private static final int[] ZERO_MAP_PADDING = {0, 0, 0, 0};
+ private static final double NAVIGATION_MAXIMUM_MAP_ZOOM = 18d;
private MapboxMap mapboxMap;
private NavigationCamera mapCamera;
@@ -486,17 +488,17 @@ public void takeScreenshot(NavigationSnapshotReadyCallback navigationSnapshotRea
mapboxMap.snapshot(navigationSnapshotReadyCallback);
}
+ @SuppressLint("MissingPermission")
private void initializeLocationComponent(MapView mapView, MapboxMap map) {
+ locationComponent = map.getLocationComponent();
+ map.setMinZoomPreference(NAVIGATION_MINIMUM_MAP_ZOOM);
+ map.setMaxZoomPreference(NAVIGATION_MAXIMUM_MAP_ZOOM);
Context context = mapView.getContext();
int locationLayerStyleRes = ThemeSwitcher.retrieveNavigationViewStyle(context,
R.attr.navigationViewLocationLayerStyle);
-
LocationComponentOptions locationComponentOptions =
LocationComponentOptions.createFromAttributes(context, locationLayerStyleRes);
- locationComponentOptions = locationComponentOptions.toBuilder().minZoom(NAVIGATION_MINIMUM_MAP_ZOOM).build();
-
- locationComponent = map.getLocationComponent();
- locationComponent.activateLocationComponent(context, null, locationComponentOptions);
+ locationComponent.activateLocationComponent(context, map.getStyle(), locationComponentOptions);
locationComponent.setLocationComponentEnabled(true);
locationComponent.setRenderMode(RenderMode.GPS);
}
@@ -521,14 +523,14 @@ private void initializeMapLayerInteractor(MapboxMap mapboxMap) {
private void initializeStreetsSource(MapboxMap mapboxMap) {
VectorSource streetSource = new VectorSource(STREETS_SOURCE_ID, MAPBOX_STREETS_V7);
- mapboxMap.addSource(streetSource);
+ mapboxMap.getStyle().addSource(streetSource);
LineLayer streetsLayer = new LineLayer(STREETS_LAYER_ID, STREETS_SOURCE_ID)
.withProperties(
lineWidth(DEFAULT_WIDTH),
lineColor(Color.WHITE)
)
.withSourceLayer(ROAD_LABEL);
- mapboxMap.addLayerAt(streetsLayer, LAST_INDEX);
+ mapboxMap.getStyle().addLayerAt(streetsLayer, LAST_INDEX);
}
private void initializeRoute(MapView mapView, MapboxMap map) {
diff --git a/libandroid-navigation-ui/src/main/java/com/mapbox/services/android/navigation/ui/v5/route/MapRouteArrow.java b/libandroid-navigation-ui/src/main/java/com/mapbox/services/android/navigation/ui/v5/route/MapRouteArrow.java
index d15f07b30b6..8baabfe36d2 100644
--- a/libandroid-navigation-ui/src/main/java/com/mapbox/services/android/navigation/ui/v5/route/MapRouteArrow.java
+++ b/libandroid-navigation-ui/src/main/java/com/mapbox/services/android/navigation/ui/v5/route/MapRouteArrow.java
@@ -173,11 +173,11 @@ private void initialize() {
SymbolLayer headLayer = createArrowHeadLayer();
SymbolLayer headCasingLayer = createArrowHeadCasingLayer();
- mapboxMap.addLayerBelow(shaftCasingLayer, LAYER_ABOVE_UPCOMING_MANEUVER_ARROW);
- mapboxMap.addLayerAbove(headCasingLayer, shaftCasingLayer.getId());
+ mapboxMap.getStyle().addLayerBelow(shaftCasingLayer, LAYER_ABOVE_UPCOMING_MANEUVER_ARROW);
+ mapboxMap.getStyle().addLayerAbove(headCasingLayer, shaftCasingLayer.getId());
- mapboxMap.addLayerAbove(shaftLayer, headCasingLayer.getId());
- mapboxMap.addLayerAbove(headLayer, shaftLayer.getId());
+ mapboxMap.getStyle().addLayerAbove(shaftLayer, headCasingLayer.getId());
+ mapboxMap.getStyle().addLayerAbove(headLayer, shaftLayer.getId());
createArrowLayerList(shaftLayer, shaftCasingLayer, headLayer, headCasingLayer);
}
@@ -188,7 +188,7 @@ private void initializeArrowShaft() {
FeatureCollection.fromFeatures(new Feature[] {}),
new GeoJsonOptions().withMaxZoom(16)
);
- mapboxMap.addSource(arrowShaftGeoJsonSource);
+ mapboxMap.getStyle().addSource(arrowShaftGeoJsonSource);
}
private void initializeArrowHead() {
@@ -197,7 +197,7 @@ private void initializeArrowHead() {
FeatureCollection.fromFeatures(new Feature[] {}),
new GeoJsonOptions().withMaxZoom(16)
);
- mapboxMap.addSource(arrowHeadGeoJsonSource);
+ mapboxMap.getStyle().addSource(arrowHeadGeoJsonSource);
}
private void addArrowHeadIcon() {
@@ -209,7 +209,7 @@ private void addArrowHeadIcon() {
Drawable head = DrawableCompat.wrap(arrowHead);
DrawableCompat.setTint(head.mutate(), arrowColor);
Bitmap icon = MapImageUtils.getBitmapFromDrawable(head);
- mapboxMap.addImage(ARROW_HEAD_ICON, icon);
+ mapboxMap.getStyle().addImage(ARROW_HEAD_ICON, icon);
}
private void addArrowHeadIconCasing() {
@@ -221,13 +221,13 @@ private void addArrowHeadIconCasing() {
Drawable headCasing = DrawableCompat.wrap(arrowHeadCasing);
DrawableCompat.setTint(headCasing.mutate(), arrowBorderColor);
Bitmap icon = MapImageUtils.getBitmapFromDrawable(headCasing);
- mapboxMap.addImage(ARROW_HEAD_ICON_CASING, icon);
+ mapboxMap.getStyle().addImage(ARROW_HEAD_ICON_CASING, icon);
}
private LineLayer createArrowShaftLayer() {
- LineLayer shaftLayer = (LineLayer) mapboxMap.getLayer(ARROW_SHAFT_LINE_LAYER_ID);
+ LineLayer shaftLayer = (LineLayer) mapboxMap.getStyle().getLayer(ARROW_SHAFT_LINE_LAYER_ID);
if (shaftLayer != null) {
- mapboxMap.removeLayer(shaftLayer);
+ mapboxMap.getStyle().removeLayer(shaftLayer);
}
return new LineLayer(ARROW_SHAFT_LINE_LAYER_ID, ARROW_SHAFT_SOURCE_ID).withProperties(
PropertyFactory.lineColor(color(arrowColor)),
@@ -251,9 +251,9 @@ private LineLayer createArrowShaftLayer() {
}
private LineLayer createArrowShaftCasingLayer() {
- LineLayer shaftCasingLayer = (LineLayer) mapboxMap.getLayer(ARROW_SHAFT_CASING_LINE_LAYER_ID);
+ LineLayer shaftCasingLayer = (LineLayer) mapboxMap.getStyle().getLayer(ARROW_SHAFT_CASING_LINE_LAYER_ID);
if (shaftCasingLayer != null) {
- mapboxMap.removeLayer(shaftCasingLayer);
+ mapboxMap.getStyle().removeLayer(shaftCasingLayer);
}
return new LineLayer(ARROW_SHAFT_CASING_LINE_LAYER_ID, ARROW_SHAFT_SOURCE_ID).withProperties(
PropertyFactory.lineColor(color(arrowBorderColor)),
@@ -277,9 +277,9 @@ private LineLayer createArrowShaftCasingLayer() {
}
private SymbolLayer createArrowHeadLayer() {
- SymbolLayer headLayer = (SymbolLayer) mapboxMap.getLayer(ARROW_HEAD_LAYER_ID);
+ SymbolLayer headLayer = (SymbolLayer) mapboxMap.getStyle().getLayer(ARROW_HEAD_LAYER_ID);
if (headLayer != null) {
- mapboxMap.removeLayer(headLayer);
+ mapboxMap.getStyle().removeLayer(headLayer);
}
return new SymbolLayer(ARROW_HEAD_LAYER_ID, ARROW_HEAD_SOURCE_ID)
.withProperties(
@@ -306,9 +306,9 @@ private SymbolLayer createArrowHeadLayer() {
}
private SymbolLayer createArrowHeadCasingLayer() {
- SymbolLayer headCasingLayer = (SymbolLayer) mapboxMap.getLayer(ARROW_HEAD_CASING_LAYER_ID);
+ SymbolLayer headCasingLayer = (SymbolLayer) mapboxMap.getStyle().getLayer(ARROW_HEAD_CASING_LAYER_ID);
if (headCasingLayer != null) {
- mapboxMap.removeLayer(headCasingLayer);
+ mapboxMap.getStyle().removeLayer(headCasingLayer);
}
return new SymbolLayer(ARROW_HEAD_CASING_LAYER_ID, ARROW_HEAD_SOURCE_ID).withProperties(
PropertyFactory.iconImage(ARROW_HEAD_ICON_CASING),
diff --git a/libandroid-navigation-ui/src/main/java/com/mapbox/services/android/navigation/ui/v5/route/MapRouteClickListener.java b/libandroid-navigation-ui/src/main/java/com/mapbox/services/android/navigation/ui/v5/route/MapRouteClickListener.java
index 66a1de6a360..93dd5bc1f5d 100644
--- a/libandroid-navigation-ui/src/main/java/com/mapbox/services/android/navigation/ui/v5/route/MapRouteClickListener.java
+++ b/libandroid-navigation-ui/src/main/java/com/mapbox/services/android/navigation/ui/v5/route/MapRouteClickListener.java
@@ -29,13 +29,14 @@ class MapRouteClickListener implements MapboxMap.OnMapClickListener {
}
@Override
- public void onMapClick(@NonNull LatLng point) {
+ public boolean onMapClick(@NonNull LatLng point) {
HashMap routeLineStrings = routeLine.retrieveRouteLineStrings();
if (invalidMapClick(routeLineStrings)) {
- return;
+ return true;
}
List directionsRoutes = routeLine.retrieveDirectionsRoutes();
findClickedRoute(point, routeLineStrings, directionsRoutes);
+ return true;
}
void setOnRouteSelectionChangeListener(OnRouteSelectionChangeListener listener) {
diff --git a/libandroid-navigation-ui/src/main/java/com/mapbox/services/android/navigation/ui/v5/route/MapRouteLine.java b/libandroid-navigation-ui/src/main/java/com/mapbox/services/android/navigation/ui/v5/route/MapRouteLine.java
index ca52db966f7..6b7d1a6a467 100644
--- a/libandroid-navigation-ui/src/main/java/com/mapbox/services/android/navigation/ui/v5/route/MapRouteLine.java
+++ b/libandroid-navigation-ui/src/main/java/com/mapbox/services/android/navigation/ui/v5/route/MapRouteLine.java
@@ -153,12 +153,12 @@ class MapRouteLine {
GeoJsonOptions wayPointGeoJsonOptions = new GeoJsonOptions().withMaxZoom(16);
FeatureCollection emptyWayPointFeatureCollection = FeatureCollection.fromFeatures(new Feature[] {});
wayPointSource = new GeoJsonSource(WAYPOINT_SOURCE_ID, emptyWayPointFeatureCollection, wayPointGeoJsonOptions);
- mapboxMap.addSource(wayPointSource);
+ mapboxMap.getStyle().addSource(wayPointSource);
GeoJsonOptions routeLineGeoJsonOptions = new GeoJsonOptions().withMaxZoom(16);
FeatureCollection emptyRouteLineFeatureCollection = FeatureCollection.fromFeatures(new Feature[] {});
routeLineSource = new GeoJsonSource(ROUTE_SOURCE_ID, emptyRouteLineFeatureCollection, routeLineGeoJsonOptions);
- mapboxMap.addSource(routeLineSource);
+ mapboxMap.getStyle().addSource(routeLineSource);
initializeLayers(mapboxMap);
}
@@ -319,7 +319,7 @@ public void onPrimaryRouteUpdated(List updatedRouteCollection
private void findRouteBelowLayerId() {
if (belowLayer == null || belowLayer.isEmpty()) {
- List styleLayers = mapboxMap.getLayers();
+ List styleLayers = mapboxMap.getStyle().getLayers();
for (int i = 0; i < styleLayers.size(); i++) {
if (!(styleLayers.get(i) instanceof SymbolLayer)
// Avoid placing the route on top of the user location layer
@@ -345,9 +345,9 @@ private void initializeLayers(MapboxMap mapboxMap) {
}
private LineLayer initializeRouteShieldLayer(MapboxMap mapboxMap) {
- LineLayer shieldLayer = mapboxMap.getLayerAs(ROUTE_SHIELD_LAYER_ID);
+ LineLayer shieldLayer = mapboxMap.getStyle().getLayerAs(ROUTE_SHIELD_LAYER_ID);
if (shieldLayer != null) {
- mapboxMap.removeLayer(shieldLayer);
+ mapboxMap.getStyle().removeLayer(shieldLayer);
}
shieldLayer = new LineLayer(ROUTE_SHIELD_LAYER_ID, ROUTE_SOURCE_ID).withProperties(
@@ -386,9 +386,9 @@ private LineLayer initializeRouteShieldLayer(MapboxMap mapboxMap) {
}
private LineLayer initializeRouteLayer(MapboxMap mapboxMap) {
- LineLayer routeLayer = mapboxMap.getLayerAs(ROUTE_LAYER_ID);
+ LineLayer routeLayer = mapboxMap.getStyle().getLayerAs(ROUTE_LAYER_ID);
if (routeLayer != null) {
- mapboxMap.removeLayer(routeLayer);
+ mapboxMap.getStyle().removeLayer(routeLayer);
}
routeLayer = new LineLayer(ROUTE_LAYER_ID, ROUTE_SOURCE_ID).withProperties(
@@ -446,15 +446,15 @@ private LineLayer initializeRouteLayer(MapboxMap mapboxMap) {
}
private SymbolLayer initializeWayPointLayer(@NonNull MapboxMap mapboxMap) {
- SymbolLayer wayPointLayer = mapboxMap.getLayerAs(WAYPOINT_LAYER_ID);
+ SymbolLayer wayPointLayer = mapboxMap.getStyle().getLayerAs(WAYPOINT_LAYER_ID);
if (wayPointLayer != null) {
- mapboxMap.removeLayer(wayPointLayer);
+ mapboxMap.getStyle().removeLayer(wayPointLayer);
}
Bitmap bitmap = MapImageUtils.getBitmapFromDrawable(originIcon);
- mapboxMap.addImage(ORIGIN_MARKER_NAME, bitmap);
+ mapboxMap.getStyle().addImage(ORIGIN_MARKER_NAME, bitmap);
bitmap = MapImageUtils.getBitmapFromDrawable(destinationIcon);
- mapboxMap.addImage(DESTINATION_MARKER_NAME, bitmap);
+ mapboxMap.getStyle().addImage(DESTINATION_MARKER_NAME, bitmap);
wayPointLayer = new SymbolLayer(WAYPOINT_LAYER_ID, WAYPOINT_SOURCE_ID).withProperties(
iconImage(
diff --git a/libandroid-navigation-ui/src/main/java/com/mapbox/services/android/navigation/ui/v5/route/ViewRouteFetcher.java b/libandroid-navigation-ui/src/main/java/com/mapbox/services/android/navigation/ui/v5/route/ViewRouteFetcher.java
index a20ccc44d25..24fd8cd1b80 100644
--- a/libandroid-navigation-ui/src/main/java/com/mapbox/services/android/navigation/ui/v5/route/ViewRouteFetcher.java
+++ b/libandroid-navigation-ui/src/main/java/com/mapbox/services/android/navigation/ui/v5/route/ViewRouteFetcher.java
@@ -25,7 +25,7 @@ public class ViewRouteFetcher extends RouteFetcher implements RouteListener {
private final ViewRouteListener listener;
private RouteOptions routeOptions;
private DirectionsRoute currentRoute;
- private Location rawLocation;
+ private Location location;
public ViewRouteFetcher(Context context, String accessToken, ViewRouteListener listener) {
super(context, accessToken);
@@ -62,17 +62,17 @@ public void extractRouteOptions(NavigationViewOptions options) {
public void fetchRouteFromOffRouteEvent(OffRouteEvent event) {
if (OffRouteEvent.isValid(event)) {
RouteProgress routeProgress = event.getRouteProgress();
- findRouteFromRouteProgress(rawLocation, routeProgress);
+ findRouteFromRouteProgress(location, routeProgress);
}
}
/**
- * Updates this object's awareness of the raw location
+ * Updates this object's awareness of the current location.
*
- * @param rawLocation to set
+ * @param location to set
*/
- public void updateRawLocation(@NonNull Location rawLocation) {
- this.rawLocation = rawLocation;
+ public void updateLocation(@NonNull Location location) {
+ this.location = location;
}
/**
diff --git a/libandroid-navigation-ui/src/main/java/com/mapbox/services/android/navigation/ui/v5/utils/MapUtils.java b/libandroid-navigation-ui/src/main/java/com/mapbox/services/android/navigation/ui/v5/utils/MapUtils.java
index 51d75b45222..d80371dd1b8 100644
--- a/libandroid-navigation-ui/src/main/java/com/mapbox/services/android/navigation/ui/v5/utils/MapUtils.java
+++ b/libandroid-navigation-ui/src/main/java/com/mapbox/services/android/navigation/ui/v5/utils/MapUtils.java
@@ -27,13 +27,13 @@ private MapUtils() {
*/
public static void addLayerToMap(@NonNull MapboxMap mapboxMap, @NonNull Layer layer,
@Nullable String idBelowLayer) {
- if (mapboxMap.getLayer(layer.getId()) != null) {
+ if (mapboxMap.getStyle().getLayer(layer.getId()) != null) {
return;
}
if (idBelowLayer == null) {
- mapboxMap.addLayer(layer);
+ mapboxMap.getStyle().addLayer(layer);
} else {
- mapboxMap.addLayerBelow(layer, idBelowLayer);
+ mapboxMap.getStyle().addLayerBelow(layer, idBelowLayer);
}
}
}
diff --git a/libandroid-navigation-ui/src/main/res/layout/navigation_view_layout.xml b/libandroid-navigation-ui/src/main/res/layout/navigation_view_layout.xml
index 6d7e8ac674a..169f07c1c1b 100644
--- a/libandroid-navigation-ui/src/main/res/layout/navigation_view_layout.xml
+++ b/libandroid-navigation-ui/src/main/res/layout/navigation_view_layout.xml
@@ -11,7 +11,6 @@
android:id="@+id/navigationMapView"
android:layout_width="match_parent"
android:layout_height="match_parent"
- app:mapbox_styleUrl="?attr/navigationViewMapStyle"
app:mapbox_uiAttribution="false"
app:mapbox_uiCompass="false"
app:mapbox_uiLogo="false"/>
diff --git a/libandroid-navigation-ui/src/test/java/com/mapbox/services/android/navigation/ui/v5/LocationEngineConductorTest.java b/libandroid-navigation-ui/src/test/java/com/mapbox/services/android/navigation/ui/v5/LocationEngineConductorTest.java
index a0c6df37b6a..7f6a55ac0ee 100644
--- a/libandroid-navigation-ui/src/test/java/com/mapbox/services/android/navigation/ui/v5/LocationEngineConductorTest.java
+++ b/libandroid-navigation-ui/src/test/java/com/mapbox/services/android/navigation/ui/v5/LocationEngineConductorTest.java
@@ -7,7 +7,6 @@
import com.mapbox.android.core.location.LocationEngine;
import com.mapbox.services.android.navigation.ui.v5.location.LocationEngineConductor;
-import com.mapbox.services.android.navigation.ui.v5.location.LocationEngineConductorListener;
import com.mapbox.services.android.navigation.v5.location.replay.ReplayRouteLocationEngine;
import org.junit.Test;
@@ -16,23 +15,20 @@
import static junit.framework.Assert.assertNotNull;
import static junit.framework.Assert.assertTrue;
import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
public class LocationEngineConductorTest extends BaseTest {
@Test
public void sanity() {
- LocationEngineConductorListener mockCallback = mock(LocationEngineConductorListener.class);
- LocationEngineConductor locationEngineConductor = new LocationEngineConductor(mockCallback);
+ LocationEngineConductor locationEngineConductor = new LocationEngineConductor();
assertNotNull(locationEngineConductor);
}
@Test
public void onInitWithSimulation_replayEngineIsProvided() {
- LocationEngineConductorListener mockCallback = mock(LocationEngineConductorListener.class);
- LocationEngineConductor locationEngineConductor = new LocationEngineConductor(mockCallback);
+ LocationEngineConductor locationEngineConductor = new LocationEngineConductor();
boolean simulateRouteEnabled = true;
locationEngineConductor.initializeLocationEngine(createMockContext(), null, simulateRouteEnabled);
@@ -43,8 +39,7 @@ public void onInitWithSimulation_replayEngineIsProvided() {
@Test
public void onInitWithSimulationAndCustomEngine_customEngineIsProvided() {
- LocationEngineConductorListener mockCallback = mock(LocationEngineConductorListener.class);
- LocationEngineConductor locationEngineConductor = new LocationEngineConductor(mockCallback);
+ LocationEngineConductor locationEngineConductor = new LocationEngineConductor();
LocationEngine customEngine = mock(LocationEngine.class);
boolean simulateRouteEnabled = true;
locationEngineConductor.initializeLocationEngine(createMockContext(), customEngine, simulateRouteEnabled);
@@ -54,18 +49,6 @@ public void onInitWithSimulationAndCustomEngine_customEngineIsProvided() {
assertEquals(customEngine, locationEngine);
}
- @Test
- public void onInitWithCustomEngine_customEngineIsActivated() {
- LocationEngineConductorListener mockCallback = mock(LocationEngineConductorListener.class);
- LocationEngineConductor locationEngineConductor = new LocationEngineConductor(mockCallback);
- LocationEngine customEngine = mock(LocationEngine.class);
- boolean simulateRouteEnabled = false;
-
- locationEngineConductor.initializeLocationEngine(createMockContext(), customEngine, simulateRouteEnabled);
-
- verify(customEngine).activate();
- }
-
@NonNull
private Context createMockContext() {
Context mockContext = mock(Context.class);
diff --git a/libandroid-navigation-ui/src/test/java/com/mapbox/services/android/navigation/ui/v5/camera/NavigationCameraTest.java b/libandroid-navigation-ui/src/test/java/com/mapbox/services/android/navigation/ui/v5/camera/NavigationCameraTest.java
index 391a97da136..1c60c43e619 100644
--- a/libandroid-navigation-ui/src/test/java/com/mapbox/services/android/navigation/ui/v5/camera/NavigationCameraTest.java
+++ b/libandroid-navigation-ui/src/test/java/com/mapbox/services/android/navigation/ui/v5/camera/NavigationCameraTest.java
@@ -1,29 +1,20 @@
package com.mapbox.services.android.navigation.ui.v5.camera;
-import android.location.Location;
-
-import com.mapbox.mapboxsdk.camera.CameraUpdate;
import com.mapbox.mapboxsdk.location.LocationComponent;
import com.mapbox.mapboxsdk.location.modes.CameraMode;
import com.mapbox.mapboxsdk.maps.MapboxMap;
import com.mapbox.services.android.navigation.ui.v5.BaseTest;
import com.mapbox.services.android.navigation.v5.navigation.MapboxNavigation;
-import com.mapbox.services.android.navigation.v5.navigation.camera.SimpleCamera;
import com.mapbox.services.android.navigation.v5.routeprogress.ProgressChangeListener;
import org.junit.Test;
-import java.io.IOException;
-
import static junit.framework.Assert.assertFalse;
import static junit.framework.Assert.assertNotNull;
import static junit.framework.Assert.assertTrue;
-import static org.mockito.ArgumentMatchers.any;
-import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
-import static org.mockito.Mockito.when;
public class NavigationCameraTest extends BaseTest {
@@ -100,54 +91,10 @@ public void onResumeWithNullLocation_progressListenerIsAdded() {
verify(navigation, times(1)).addProgressChangeListener(listener);
}
- @Test
- public void resetCameraPositionWith_mapCameraAnimates() throws IOException {
- MapboxMap mapboxMap = mock(MapboxMap.class);
- MapboxNavigation navigation = mock(MapboxNavigation.class);
- when(navigation.getCameraEngine()).thenReturn(new SimpleCamera());
- LocationComponent locationComponent = mock(LocationComponent.class);
- Location location = buildMockLocation();
- when(locationComponent.getLastKnownLocation()).thenReturn(location);
- NavigationCamera camera = new NavigationCamera(mapboxMap, navigation, locationComponent);
- camera.start(buildTestDirectionsRoute());
-
- camera.resetCameraPositionWith(NavigationCamera.NAVIGATION_TRACKING_MODE_GPS);
-
- verify(mapboxMap).animateCamera(any(CameraUpdate.class), anyInt(), any(MapboxMap.CancelableCallback.class));
- }
-
- @Test
- public void resetCameraPositionWith_nullLocationIsIgnored() throws IOException {
- MapboxMap mapboxMap = mock(MapboxMap.class);
- MapboxNavigation navigation = mock(MapboxNavigation.class);
- when(navigation.getCameraEngine()).thenReturn(new SimpleCamera());
- LocationComponent locationComponent = mock(LocationComponent.class);
- when(locationComponent.getLastKnownLocation()).thenReturn(null);
- NavigationCamera camera = new NavigationCamera(mapboxMap, navigation, locationComponent);
- camera.start(buildTestDirectionsRoute());
-
- camera.resetCameraPositionWith(NavigationCamera.NAVIGATION_TRACKING_MODE_GPS);
-
- verify(mapboxMap, times(0)).animateCamera(any(CameraUpdate.class),
- anyInt(), any(MapboxMap.CancelableCallback.class));
- }
-
- private Location buildMockLocation() {
- Location location = mock(Location.class);
- when(location.getLatitude()).thenReturn(1.234);
- when(location.getLongitude()).thenReturn(1.234);
- when(location.getBearing()).thenReturn(1f);
- return location;
- }
-
private NavigationCamera buildCamera() {
return new NavigationCamera(mock(MapboxMap.class), mock(MapboxNavigation.class), mock(LocationComponent.class));
}
- private NavigationCamera buildCamera(MapboxMap map, LocationComponent locationComponent) {
- return new NavigationCamera(map, mock(MapboxNavigation.class), locationComponent);
- }
-
private NavigationCamera buildCamera(LocationComponent locationComponent) {
return new NavigationCamera(mock(MapboxMap.class), mock(MapboxNavigation.class), locationComponent);
}
diff --git a/libandroid-navigation-ui/src/test/java/com/mapbox/services/android/navigation/ui/v5/camera/ResetTrackingModeCancelableCallbackTest.java b/libandroid-navigation-ui/src/test/java/com/mapbox/services/android/navigation/ui/v5/camera/ResetTrackingModeCancelableCallbackTest.java
deleted file mode 100644
index 36a72a0afad..00000000000
--- a/libandroid-navigation-ui/src/test/java/com/mapbox/services/android/navigation/ui/v5/camera/ResetTrackingModeCancelableCallbackTest.java
+++ /dev/null
@@ -1,32 +0,0 @@
-package com.mapbox.services.android.navigation.ui.v5.camera;
-
-import org.junit.Test;
-
-import static org.mockito.ArgumentMatchers.eq;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.verify;
-
-public class ResetTrackingModeCancelableCallbackTest {
-
- @Test
- public void onCancel_trackingModeIsSet() {
- NavigationCamera camera = mock(NavigationCamera.class);
- int trackingMode = NavigationCamera.NAVIGATION_TRACKING_MODE_GPS;
- ResetTrackingModeCancelableCallback callback = new ResetTrackingModeCancelableCallback(camera, trackingMode);
-
- callback.onCancel();
-
- verify(camera).updateCameraTrackingMode(eq(trackingMode));
- }
-
- @Test
- public void onFinish_trackingModeIsSet() {
- NavigationCamera camera = mock(NavigationCamera.class);
- int trackingMode = NavigationCamera.NAVIGATION_TRACKING_MODE_GPS;
- ResetTrackingModeCancelableCallback callback = new ResetTrackingModeCancelableCallback(camera, trackingMode);
-
- callback.onFinish();
-
- verify(camera).updateCameraTrackingMode(eq(trackingMode));
- }
-}
\ No newline at end of file
diff --git a/libandroid-navigation-ui/src/test/java/com/mapbox/services/android/navigation/ui/v5/map/MapLayerInteractorTest.java b/libandroid-navigation-ui/src/test/java/com/mapbox/services/android/navigation/ui/v5/map/MapLayerInteractorTest.java
index 61d4115e978..56f3ae0cd23 100644
--- a/libandroid-navigation-ui/src/test/java/com/mapbox/services/android/navigation/ui/v5/map/MapLayerInteractorTest.java
+++ b/libandroid-navigation-ui/src/test/java/com/mapbox/services/android/navigation/ui/v5/map/MapLayerInteractorTest.java
@@ -1,6 +1,7 @@
package com.mapbox.services.android.navigation.ui.v5.map;
import com.mapbox.mapboxsdk.maps.MapboxMap;
+import com.mapbox.mapboxsdk.maps.Style;
import com.mapbox.mapboxsdk.style.layers.CircleLayer;
import com.mapbox.mapboxsdk.style.layers.HeatmapLayer;
import com.mapbox.mapboxsdk.style.layers.Layer;
@@ -31,7 +32,8 @@ public void updateLayerVisibility_visibilityIsSet() {
when(anySymbolOrLineLayer.getSourceLayer()).thenReturn("any");
List layers = buildLayerListWith(anySymbolOrLineLayer);
MapboxMap map = mock(MapboxMap.class);
- when(map.getLayers()).thenReturn(layers);
+ when(map.getStyle()).thenReturn(mock(Style.class));
+ when(map.getStyle().getLayers()).thenReturn(layers);
MapLayerInteractor layerInteractor = new MapLayerInteractor(map);
layerInteractor.updateLayerVisibility(true, "any");
@@ -45,7 +47,8 @@ public void updateLayerVisibility_visibilityIsNotSet() {
when(anySymbolOrLineLayer.getSourceLayer()).thenReturn("any");
List layers = buildLayerListWith(anySymbolOrLineLayer);
MapboxMap map = mock(MapboxMap.class);
- when(map.getLayers()).thenReturn(layers);
+ when(map.getStyle()).thenReturn(mock(Style.class));
+ when(map.getStyle().getLayers()).thenReturn(layers);
MapLayerInteractor layerInteractor = new MapLayerInteractor(map);
layerInteractor.updateLayerVisibility(true, "random");
@@ -58,7 +61,8 @@ public void updateLayerVisibility_visibilityIsNotSetIfInvalidLayer() {
CircleLayer invalidLayer = mock(CircleLayer.class);
List layers = buildLayerListWith(invalidLayer);
MapboxMap map = mock(MapboxMap.class);
- when(map.getLayers()).thenReturn(layers);
+ when(map.getStyle()).thenReturn(mock(Style.class));
+ when(map.getStyle().getLayers()).thenReturn(layers);
MapLayerInteractor layerInteractor = new MapLayerInteractor(map);
layerInteractor.updateLayerVisibility(true, "circle");
@@ -73,7 +77,8 @@ public void isLayerVisible_visibleReturnsTrue() {
when(anySymbolOrLineLayer.getVisibility()).thenReturn(visibility(Property.VISIBLE));
List layers = buildLayerListWith(anySymbolOrLineLayer);
MapboxMap map = mock(MapboxMap.class);
- when(map.getLayers()).thenReturn(layers);
+ when(map.getStyle()).thenReturn(mock(Style.class));
+ when(map.getStyle().getLayers()).thenReturn(layers);
MapLayerInteractor layerInteractor = new MapLayerInteractor(map);
boolean isVisible = layerInteractor.isLayerVisible("any");
@@ -88,7 +93,8 @@ public void isLayerVisible_visibleReturnsFalse() {
when(anySymbolOrLineLayer.getVisibility()).thenReturn(visibility(Property.NONE));
List layers = buildLayerListWith(anySymbolOrLineLayer);
MapboxMap map = mock(MapboxMap.class);
- when(map.getLayers()).thenReturn(layers);
+ when(map.getStyle()).thenReturn(mock(Style.class));
+ when(map.getStyle().getLayers()).thenReturn(layers);
MapLayerInteractor layerInteractor = new MapLayerInteractor(map);
boolean isVisible = layerInteractor.isLayerVisible("any");
@@ -101,7 +107,8 @@ public void isLayerVisible_visibleReturnsFalseIfInvalidLayer() {
HeatmapLayer invalidLayer = mock(HeatmapLayer.class);
List layers = buildLayerListWith(invalidLayer);
MapboxMap map = mock(MapboxMap.class);
- when(map.getLayers()).thenReturn(layers);
+ when(map.getStyle()).thenReturn(mock(Style.class));
+ when(map.getStyle().getLayers()).thenReturn(layers);
MapLayerInteractor layerInteractor = new MapLayerInteractor(map);
boolean isVisible = layerInteractor.isLayerVisible("heatmap");
diff --git a/libandroid-navigation/src/main/java/com/mapbox/services/android/navigation/v5/location/replay/ReplayRouteLocationEngine.java b/libandroid-navigation/src/main/java/com/mapbox/services/android/navigation/v5/location/replay/ReplayRouteLocationEngine.java
index 8ca53034857..637d80f551b 100644
--- a/libandroid-navigation/src/main/java/com/mapbox/services/android/navigation/v5/location/replay/ReplayRouteLocationEngine.java
+++ b/libandroid-navigation/src/main/java/com/mapbox/services/android/navigation/v5/location/replay/ReplayRouteLocationEngine.java
@@ -1,13 +1,16 @@
package com.mapbox.services.android.navigation.v5.location.replay;
-import android.annotation.SuppressLint;
+import android.app.PendingIntent;
import android.location.Location;
import android.os.Handler;
+import android.os.Looper;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import com.mapbox.android.core.location.LocationEngine;
-import com.mapbox.android.core.location.LocationEngineListener;
+import com.mapbox.android.core.location.LocationEngineCallback;
+import com.mapbox.android.core.location.LocationEngineRequest;
+import com.mapbox.android.core.location.LocationEngineResult;
import com.mapbox.api.directions.v5.models.DirectionsRoute;
import com.mapbox.geojson.LineString;
import com.mapbox.geojson.Point;
@@ -15,8 +18,10 @@
import java.util.ArrayList;
import java.util.List;
+import timber.log.Timber;
-public class ReplayRouteLocationEngine extends LocationEngine implements Runnable {
+
+public class ReplayRouteLocationEngine implements LocationEngine, Runnable {
private static final int HEAD = 0;
private static final int MOCKED_POINTS_LEFT_THRESHOLD = 5;
@@ -36,37 +41,23 @@ public class ReplayRouteLocationEngine extends LocationEngine implements Runnabl
private Handler handler;
private List mockedLocations;
private ReplayLocationDispatcher dispatcher;
+ private ReplayRouteLocationListener replayLocationListener;
private Location lastLocation = null;
- private final ReplayLocationListener replayLocationListener = new ReplayLocationListener() {
- @Override
- public void onLocationReplay(Location location) {
- for (LocationEngineListener listener : locationListeners) {
- listener.onLocationChanged(location);
- }
- lastLocation = location;
- if (!mockedLocations.isEmpty()) {
- mockedLocations.remove(HEAD);
- }
- }
- };
+ private DirectionsRoute route = null;
+ private Point point = null;
public ReplayRouteLocationEngine() {
this.handler = new Handler();
}
- @SuppressLint("MissingPermission")
public void assign(DirectionsRoute route) {
- start(route);
+ this.route = route;
+ this.point = null;
}
- @SuppressLint("MissingPermission")
public void moveTo(Point point) {
- Location lastLocation = getLastLocation();
- if (lastLocation == null) {
- return;
- }
-
- startRoute(point, lastLocation);
+ this.point = point;
+ this.route = null;
}
public void assignLastLocation(Point currentPosition) {
@@ -105,96 +96,85 @@ public void run() {
scheduleNextDispatch();
}
- /**
- * Connect all the location listeners.
- */
@Override
- public void activate() {
- for (LocationEngineListener listener : locationListeners) {
- listener.onConnected();
+ public void getLastLocation(@NonNull LocationEngineCallback callback) throws SecurityException {
+ if (lastLocation == null) {
+ callback.onFailure(new Exception("Last location can't be null"));
+ return;
}
+ callback.onSuccess(LocationEngineResult.create(lastLocation));
}
@Override
- public void deactivate() {
- if (dispatcher != null) {
- dispatcher.stop();
- }
- handler.removeCallbacks(this);
+ public void requestLocationUpdates(@NonNull LocationEngineRequest request,
+ @NonNull LocationEngineCallback callback,
+ @Nullable Looper looper) throws SecurityException {
+ beginReplayWith(callback);
}
- /**
- * While the {@link ReplayRouteLocationEngine} is in use, you are always connected to it.
- *
- * @return true.
- */
@Override
- public boolean isConnected() {
- return true;
+ public void requestLocationUpdates(@NonNull LocationEngineRequest request,
+ PendingIntent pendingIntent) throws SecurityException {
+ Timber.e("ReplayEngine does not support PendingIntent.");
}
- @SuppressLint("MissingPermission")
@Override
- @Nullable
- public Location getLastLocation() {
- return lastLocation;
+ public void removeLocationUpdates(@NonNull LocationEngineCallback callback) {
+ deactivate();
}
- /**
- * Nothing needs to happen here since we are mocking the user location along a route.
- */
@Override
- public void requestLocationUpdates() {
+ public void removeLocationUpdates(PendingIntent pendingIntent) {
+ Timber.e("ReplayEngine does not support PendingIntent.");
+ }
+ void updateLastLocation(Location lastLocation) {
+ this.lastLocation = lastLocation;
}
- /**
- * Removes location updates for the LocationListener.
- */
- @Override
- public void removeLocationUpdates() {
- for (LocationEngineListener listener : locationListeners) {
- locationListeners.remove(listener);
- }
- if (dispatcher != null) {
- dispatcher.removeReplayLocationListener(replayLocationListener);
+ void removeLastMockedLocation() {
+ if (!mockedLocations.isEmpty()) {
+ mockedLocations.remove(HEAD);
}
}
- @Override
- public Type obtainType() {
- return Type.MOCK;
+ private void deactivate() {
+ if (dispatcher != null) {
+ dispatcher.stop();
+ }
+ handler.removeCallbacks(this);
}
- private void start(DirectionsRoute route) {
+ private void start(DirectionsRoute route, LocationEngineCallback callback) {
handler.removeCallbacks(this);
converter = new ReplayRouteLocationConverter(route, speed, delay);
converter.initializeTime();
mockedLocations = converter.toLocations();
- dispatcher = obtainDispatcher();
+ dispatcher = obtainDispatcher(callback);
dispatcher.run();
scheduleNextDispatch();
}
- private ReplayLocationDispatcher obtainDispatcher() {
- if (dispatcher != null) {
+ private ReplayLocationDispatcher obtainDispatcher(LocationEngineCallback callback) {
+ if (dispatcher != null && replayLocationListener != null) {
dispatcher.stop();
dispatcher.removeReplayLocationListener(replayLocationListener);
}
dispatcher = new ReplayLocationDispatcher(mockedLocations);
+ replayLocationListener = new ReplayRouteLocationListener(this, callback);
dispatcher.addReplayLocationListener(replayLocationListener);
return dispatcher;
}
- private void startRoute(Point point, Location lastLocation) {
+ private void startRoute(Point point, Location lastLocation, LocationEngineCallback callback) {
handler.removeCallbacks(this);
converter.updateSpeed(speed);
converter.updateDelay(delay);
converter.initializeTime();
LineString route = obtainRoute(point, lastLocation);
mockedLocations = converter.calculateMockLocations(converter.sliceRoute(route));
- dispatcher = obtainDispatcher();
+ dispatcher = obtainDispatcher(callback);
dispatcher.run();
}
@@ -217,6 +197,20 @@ private void scheduleNextDispatch() {
}
}
+ private void beginReplayWith(@NonNull LocationEngineCallback callback) {
+ if (route != null) {
+ start(route, callback);
+ } else if (point != null) {
+ if (lastLocation == null) {
+ callback.onFailure(new Exception("Cannot move to point without last location assigned."));
+ return;
+ }
+ startRoute(point, lastLocation, callback);
+ } else {
+ callback.onFailure(new Exception("No route found to replay."));
+ }
+ }
+
private void initializeLastLocation() {
if (lastLocation == null) {
lastLocation = new Location(REPLAY_ROUTE);
diff --git a/libandroid-navigation/src/main/java/com/mapbox/services/android/navigation/v5/location/replay/ReplayRouteLocationListener.java b/libandroid-navigation/src/main/java/com/mapbox/services/android/navigation/v5/location/replay/ReplayRouteLocationListener.java
new file mode 100644
index 00000000000..c2a3a391795
--- /dev/null
+++ b/libandroid-navigation/src/main/java/com/mapbox/services/android/navigation/v5/location/replay/ReplayRouteLocationListener.java
@@ -0,0 +1,26 @@
+package com.mapbox.services.android.navigation.v5.location.replay;
+
+import android.location.Location;
+
+import com.mapbox.android.core.location.LocationEngineCallback;
+import com.mapbox.android.core.location.LocationEngineResult;
+
+class ReplayRouteLocationListener implements ReplayLocationListener {
+
+ private final ReplayRouteLocationEngine engine;
+ private final LocationEngineCallback callback;
+
+ ReplayRouteLocationListener(ReplayRouteLocationEngine engine,
+ LocationEngineCallback callback) {
+ this.engine = engine;
+ this.callback = callback;
+ }
+
+ @Override
+ public void onLocationReplay(Location location) {
+ engine.updateLastLocation(location);
+ engine.removeLastMockedLocation();
+ LocationEngineResult result = LocationEngineResult.create(location);
+ callback.onSuccess(result);
+ }
+}
diff --git a/libandroid-navigation/src/main/java/com/mapbox/services/android/navigation/v5/navigation/LocationUpdater.java b/libandroid-navigation/src/main/java/com/mapbox/services/android/navigation/v5/navigation/LocationUpdater.java
new file mode 100644
index 00000000000..6ed87b33228
--- /dev/null
+++ b/libandroid-navigation/src/main/java/com/mapbox/services/android/navigation/v5/navigation/LocationUpdater.java
@@ -0,0 +1,86 @@
+package com.mapbox.services.android.navigation.v5.navigation;
+
+import android.annotation.SuppressLint;
+import android.location.Location;
+import android.support.annotation.NonNull;
+
+import com.mapbox.android.core.location.LocationEngine;
+import com.mapbox.android.core.location.LocationEngineCallback;
+import com.mapbox.android.core.location.LocationEngineRequest;
+import com.mapbox.android.core.location.LocationEngineResult;
+
+import java.lang.ref.WeakReference;
+
+import timber.log.Timber;
+
+class LocationUpdater {
+
+ private final LocationEngineCallback callback = new CurrentLocationEngineCallback(this);
+ private final RouteProcessorBackgroundThread thread;
+ private LocationEngine locationEngine;
+ private LocationEngineRequest request;
+
+ @SuppressLint("MissingPermission")
+ LocationUpdater(RouteProcessorBackgroundThread thread, LocationEngine locationEngine,
+ LocationEngineRequest request) {
+ this.thread = thread;
+ this.locationEngine = locationEngine;
+ this.request = request;
+ requestInitialLocationUpdates(locationEngine, request);
+ }
+
+ void updateLocationEngine(LocationEngine locationEngine) {
+ requestLocationUpdates(request, locationEngine);
+ this.locationEngine = locationEngine;
+ }
+
+ void updateLocationEngineRequest(LocationEngineRequest request) {
+ requestLocationUpdates(request, locationEngine);
+ this.request = request;
+ }
+
+ void onLocationChanged(Location location) {
+ if (location != null) {
+ thread.updateLocation(location);
+ NavigationTelemetry.getInstance().updateLocation(location);
+ }
+ }
+
+ void removeLocationUpdates() {
+ locationEngine.removeLocationUpdates(callback);
+ }
+
+ @SuppressLint("MissingPermission")
+ private void requestInitialLocationUpdates(LocationEngine locationEngine, LocationEngineRequest request) {
+ locationEngine.requestLocationUpdates(request, callback, null);
+ }
+
+ @SuppressLint("MissingPermission")
+ private void requestLocationUpdates(LocationEngineRequest request, LocationEngine locationEngine) {
+ this.locationEngine.removeLocationUpdates(callback);
+ locationEngine.requestLocationUpdates(request, callback, null);
+ }
+
+ static class CurrentLocationEngineCallback implements LocationEngineCallback {
+
+ private final WeakReference updaterWeakReference;
+
+ CurrentLocationEngineCallback(LocationUpdater locationUpdater) {
+ this.updaterWeakReference = new WeakReference<>(locationUpdater);
+ }
+
+ @Override
+ public void onSuccess(LocationEngineResult result) {
+ LocationUpdater locationUpdater = updaterWeakReference.get();
+ if (locationUpdater != null) {
+ Location location = result.getLastLocation();
+ locationUpdater.onLocationChanged(location);
+ }
+ }
+
+ @Override
+ public void onFailure(@NonNull Exception exception) {
+ Timber.e(exception);
+ }
+ }
+}
\ No newline at end of file
diff --git a/libandroid-navigation/src/main/java/com/mapbox/services/android/navigation/v5/navigation/MapboxNavigation.java b/libandroid-navigation/src/main/java/com/mapbox/services/android/navigation/v5/navigation/MapboxNavigation.java
index f949f4e641c..869b23b4547 100644
--- a/libandroid-navigation/src/main/java/com/mapbox/services/android/navigation/v5/navigation/MapboxNavigation.java
+++ b/libandroid-navigation/src/main/java/com/mapbox/services/android/navigation/v5/navigation/MapboxNavigation.java
@@ -10,8 +10,8 @@
import android.support.annotation.Nullable;
import com.mapbox.android.core.location.LocationEngine;
-import com.mapbox.android.core.location.LocationEnginePriority;
import com.mapbox.android.core.location.LocationEngineProvider;
+import com.mapbox.android.core.location.LocationEngineRequest;
import com.mapbox.api.directions.v5.models.DirectionsRoute;
import com.mapbox.navigator.Navigator;
import com.mapbox.services.android.navigation.v5.milestone.BannerInstructionMilestone;
@@ -51,6 +51,8 @@
*/
public class MapboxNavigation implements ServiceConnection {
+ private static final long UPDATE_INTERVAL_IN_MILLISECONDS = 1000;
+ private static final long FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS = 500;
private NavigationEventDispatcher navigationEventDispatcher;
private NavigationEngineFactory navigationEngineFactory;
private NavigationTelemetry navigationTelemetry = null;
@@ -58,7 +60,8 @@ public class MapboxNavigation implements ServiceConnection {
private MapboxNavigator mapboxNavigator;
private DirectionsRoute directionsRoute;
private MapboxNavigationOptions options;
- private LocationEngine locationEngine = null;
+ private LocationEngine locationEngine;
+ private LocationEngineRequest locationEngineRequest;
private Set milestones;
private final String accessToken;
private Context applicationContext;
@@ -167,7 +170,6 @@ public MapboxNavigation(@NonNull Context context, @NonNull String accessToken,
*/
public void onDestroy() {
stopNavigation();
- disableLocationEngine();
removeOffRouteListener(null);
removeProgressChangeListener(null);
removeMilestoneEventListener(null);
@@ -255,29 +257,18 @@ public void removeMilestone(int milestoneIdentifier) {
/**
* Navigation needs an instance of location engine in order to acquire user location information
- * and handle events based off of the current information. By default, a LOST location engine is
- * created with the optimal navigation settings. Passing in a custom location engine using this
- * API assumes you have set it to the ideal parameters which are specified below.
+ * and handle events based off of the current information. By default, a {@link LocationEngine} is
+ * created using {@link LocationEngineProvider#getBestLocationEngine(Context)}.
*
- * Although it is not required to set your location engine to these parameters, these values are
- * what we found works best. Note that this also depends on which underlying location service you
- * are using. Reference the corresponding location service documentation for more information and
- * way's you could improve the performance.
- *
- * An ideal conditions, the Navigation SDK will receive location updates once every second with
+ * In ideal conditions, the Navigation SDK will receive location updates once every second with
* mild to high horizontal accuracy. The location update must also contain all information an
* Android location object would expect including bearing, speed, timestamp, and
* latitude/longitude.
- *
- * Listed below are the ideal conditions for both a LOST location engine and a Google Play
- * Services Location engine.
- *
- * Set the location priority to {@code HIGH_ACCURACY}.
- * The fastest interval should be set around 1 second (1000ms). Note that the interval isn't
- * a guaranteed to match this value exactly and is only an estimate.
- * Setting the location engine interval to 0 will result in location updates occurring as
- * quickly as possible within the fastest interval limit placed on it.
- *
+ *
+ *
+ * This method can be called during an active navigation session. The active {@link LocationEngine} will be
+ * replaced and the new one (passed via this method) will be activated with the current {@link LocationEngineRequest}.
+ *
*
* @param locationEngine a {@link LocationEngine} used for the navigation session
* @since 0.1.0
@@ -285,7 +276,7 @@ public void removeMilestone(int milestoneIdentifier) {
public void setLocationEngine(@NonNull LocationEngine locationEngine) {
this.locationEngine = locationEngine;
// Setup telemetry with new engine
- navigationTelemetry.updateLocationEngine(locationEngine);
+ navigationTelemetry.updateLocationEngineName(locationEngine);
// Notify service to get new location engine.
if (isServiceAvailable()) {
navigationService.updateLocationEngine(locationEngine);
@@ -307,6 +298,27 @@ public LocationEngine getLocationEngine() {
return locationEngine;
}
+ /**
+ * This method updates the {@link LocationEngineRequest} that is used with the {@link LocationEngine}.
+ *
+ * If a request is not provided via {@link MapboxNavigation#setLocationEngineRequest(LocationEngineRequest)},
+ * a default will be provided with optimized settings for navigation.
+ *
+ *
+ * This method can be called during an active navigation session. The active {@link LocationEngineRequest} will be
+ * replaced and the new one (passed via this method) will be activated with the current {@link LocationEngine}.
+ *
+ *
+ * @param locationEngineRequest to be used with the current {@link LocationEngine}
+ */
+ public void setLocationEngineRequest(@NonNull LocationEngineRequest locationEngineRequest) {
+ this.locationEngineRequest = locationEngineRequest;
+
+ if (isServiceAvailable()) {
+ navigationService.updateLocationEngineRequest(locationEngineRequest);
+ }
+ }
+
/**
* Calling This begins a new navigation session using the provided directions route. this API is
* also intended to be used when a reroute occurs passing in the updated directions route.
@@ -711,7 +723,7 @@ public void cancelFeedback(String feedbackId) {
/**
* Use this method to update the leg index of the current {@link DirectionsRoute}
* being traveled along.
- *
+ *
* An index passed here that is not valid will be ignored. Please note, the leg index
* will automatically increment by default. To disable this,
* use {@link MapboxNavigationOptions#enableAutoIncrementLegIndex()}.
@@ -783,11 +795,17 @@ MapboxNavigator retrieveMapboxNavigator() {
return mapboxNavigator;
}
+ @NonNull
+ LocationEngineRequest retrieveLocationEngineRequest() {
+ return locationEngineRequest;
+ }
+
private void initializeForTest() {
// Initialize event dispatcher and add internal listeners
navigationEventDispatcher = new NavigationEventDispatcher();
navigationEngineFactory = new NavigationEngineFactory();
- initializeDefaultLocationEngine();
+ locationEngine = obtainLocationEngine();
+ locationEngineRequest = obtainLocationEngineRequest();
initializeTelemetry();
// Create and add default milestones if enabled.
@@ -808,7 +826,8 @@ private void initialize() {
mapboxNavigator = new MapboxNavigator(new Navigator());
navigationEventDispatcher = new NavigationEventDispatcher();
navigationEngineFactory = new NavigationEngineFactory();
- initializeDefaultLocationEngine();
+ locationEngine = obtainLocationEngine();
+ locationEngineRequest = obtainLocationEngineRequest();
initializeTelemetry();
// Create and add default milestones if enabled.
@@ -838,34 +857,25 @@ private NavigationTelemetry obtainTelemetry() {
return navigationTelemetry;
}
- /**
- * Since navigation requires location information there should always be a valid location engine
- * which we can use to get information. Therefore, by default we build one.
- */
- private void initializeDefaultLocationEngine() {
- locationEngine = obtainLocationEngine();
- locationEngine.setPriority(LocationEnginePriority.HIGH_ACCURACY);
- locationEngine.setFastestInterval(1000);
- locationEngine.setInterval(0);
- locationEngine.activate();
- }
-
+ @NonNull
private LocationEngine obtainLocationEngine() {
if (locationEngine == null) {
- return new LocationEngineProvider(applicationContext).obtainBestLocationEngineAvailable();
+ return LocationEngineProvider.getBestLocationEngine(applicationContext);
}
return locationEngine;
}
- /**
- * When onDestroy gets called, it is safe to remove location updates and deactivate the engine.
- */
- private void disableLocationEngine() {
- if (locationEngine != null) {
- locationEngine.removeLocationUpdates();
- locationEngine.deactivate();
+ @NonNull
+ private LocationEngineRequest obtainLocationEngineRequest() {
+ if (locationEngineRequest == null) {
+ return new LocationEngineRequest.Builder(UPDATE_INTERVAL_IN_MILLISECONDS)
+ .setPriority(LocationEngineRequest.PRIORITY_HIGH_ACCURACY)
+ .setFastestInterval(FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS)
+ .build();
}
+
+ return locationEngineRequest;
}
private void startNavigationWith(@NonNull DirectionsRoute directionsRoute) {
diff --git a/libandroid-navigation/src/main/java/com/mapbox/services/android/navigation/v5/navigation/NavigationLocationEngineListener.java b/libandroid-navigation/src/main/java/com/mapbox/services/android/navigation/v5/navigation/NavigationLocationEngineListener.java
deleted file mode 100644
index 29fdd84c22a..00000000000
--- a/libandroid-navigation/src/main/java/com/mapbox/services/android/navigation/v5/navigation/NavigationLocationEngineListener.java
+++ /dev/null
@@ -1,40 +0,0 @@
-package com.mapbox.services.android.navigation.v5.navigation;
-
-import android.annotation.SuppressLint;
-import android.location.Location;
-
-import com.mapbox.android.core.location.LocationEngine;
-import com.mapbox.android.core.location.LocationEngineListener;
-
-class NavigationLocationEngineListener implements LocationEngineListener {
-
- private final RouteProcessorBackgroundThread thread;
- private final LocationEngine locationEngine;
-
- NavigationLocationEngineListener(RouteProcessorBackgroundThread thread, LocationEngine locationEngine) {
- this.thread = thread;
- this.locationEngine = locationEngine;
- }
-
- @Override
- @SuppressWarnings("MissingPermission")
- public void onConnected() {
- locationEngine.requestLocationUpdates();
- sendLastKnownLocation();
- }
-
- @Override
- public void onLocationChanged(Location location) {
- if (location != null) {
- thread.updateRawLocation(location);
- }
- }
-
- @SuppressLint("MissingPermission")
- private void sendLastKnownLocation() {
- Location lastLocation = locationEngine.getLastLocation();
- if (lastLocation != null) {
- onLocationChanged(lastLocation);
- }
- }
-}
\ No newline at end of file
diff --git a/libandroid-navigation/src/main/java/com/mapbox/services/android/navigation/v5/navigation/NavigationLocationEngineUpdater.java b/libandroid-navigation/src/main/java/com/mapbox/services/android/navigation/v5/navigation/NavigationLocationEngineUpdater.java
deleted file mode 100644
index 643318c6b92..00000000000
--- a/libandroid-navigation/src/main/java/com/mapbox/services/android/navigation/v5/navigation/NavigationLocationEngineUpdater.java
+++ /dev/null
@@ -1,25 +0,0 @@
-package com.mapbox.services.android.navigation.v5.navigation;
-
-import com.mapbox.android.core.location.LocationEngine;
-
-class NavigationLocationEngineUpdater {
-
- private final NavigationLocationEngineListener listener;
- private LocationEngine locationEngine;
-
- NavigationLocationEngineUpdater(LocationEngine locationEngine, NavigationLocationEngineListener listener) {
- this.locationEngine = locationEngine;
- this.listener = listener;
- locationEngine.addLocationEngineListener(listener);
- }
-
- void updateLocationEngine(LocationEngine locationEngine) {
- removeLocationEngineListener();
- this.locationEngine = locationEngine;
- locationEngine.addLocationEngineListener(listener);
- }
-
- void removeLocationEngineListener() {
- locationEngine.removeLocationEngineListener(listener);
- }
-}
diff --git a/libandroid-navigation/src/main/java/com/mapbox/services/android/navigation/v5/navigation/NavigationService.java b/libandroid-navigation/src/main/java/com/mapbox/services/android/navigation/v5/navigation/NavigationService.java
index cc89ae419cd..4c34cdcfa3f 100644
--- a/libandroid-navigation/src/main/java/com/mapbox/services/android/navigation/v5/navigation/NavigationService.java
+++ b/libandroid-navigation/src/main/java/com/mapbox/services/android/navigation/v5/navigation/NavigationService.java
@@ -9,6 +9,7 @@
import android.support.annotation.Nullable;
import com.mapbox.android.core.location.LocationEngine;
+import com.mapbox.android.core.location.LocationEngineRequest;
import com.mapbox.api.directions.v5.models.DirectionsRoute;
import com.mapbox.services.android.navigation.v5.navigation.notification.NavigationNotification;
import com.mapbox.services.android.navigation.v5.route.FasterRoute;
@@ -31,7 +32,7 @@ public class NavigationService extends Service {
private final IBinder localBinder = new LocalBinder();
private RouteProcessorBackgroundThread thread;
- private NavigationLocationEngineUpdater locationUpdater;
+ private LocationUpdater locationUpdater;
private RouteFetcher routeFetcher;
private NavigationNotificationProvider notificationProvider;
@@ -71,28 +72,26 @@ void startNavigation(MapboxNavigation mapboxNavigation) {
*/
void endNavigation() {
routeFetcher.clearListeners();
- locationUpdater.removeLocationEngineListener();
+ locationUpdater.removeLocationUpdates();
notificationProvider.shutdown(getApplication());
thread.quit();
}
- /**
- * Called with {@link MapboxNavigation#setLocationEngine(LocationEngine)}.
- * Updates this service with the new {@link LocationEngine}.
- *
- * @param locationEngine to update the provider
- */
void updateLocationEngine(LocationEngine locationEngine) {
locationUpdater.updateLocationEngine(locationEngine);
}
+ void updateLocationEngineRequest(LocationEngineRequest request) {
+ locationUpdater.updateLocationEngineRequest(request);
+ }
+
private void initialize(MapboxNavigation mapboxNavigation) {
NavigationEventDispatcher dispatcher = mapboxNavigation.getEventDispatcher();
String accessToken = mapboxNavigation.obtainAccessToken();
initializeRouteFetcher(dispatcher, accessToken, mapboxNavigation.retrieveEngineFactory());
initializeNotificationProvider(mapboxNavigation);
initializeRouteProcessorThread(mapboxNavigation, dispatcher, routeFetcher, notificationProvider);
- initializeLocationProvider(mapboxNavigation);
+ initializeLocationUpdater(mapboxNavigation);
}
private void initializeRouteFetcher(NavigationEventDispatcher dispatcher, String accessToken,
@@ -117,10 +116,10 @@ private void initializeRouteProcessorThread(MapboxNavigation mapboxNavigation,
thread = new RouteProcessorBackgroundThread(mapboxNavigation, new Handler(), listener);
}
- private void initializeLocationProvider(MapboxNavigation mapboxNavigation) {
+ private void initializeLocationUpdater(MapboxNavigation mapboxNavigation) {
LocationEngine locationEngine = mapboxNavigation.getLocationEngine();
- NavigationLocationEngineListener listener = new NavigationLocationEngineListener(thread, locationEngine);
- locationUpdater = new NavigationLocationEngineUpdater(locationEngine, listener);
+ LocationEngineRequest locationEngineRequest = mapboxNavigation.retrieveLocationEngineRequest();
+ locationUpdater = new LocationUpdater(thread, locationEngine, locationEngineRequest);
}
private void startForegroundNotification(NavigationNotification navigationNotification) {
diff --git a/libandroid-navigation/src/main/java/com/mapbox/services/android/navigation/v5/navigation/NavigationTelemetry.java b/libandroid-navigation/src/main/java/com/mapbox/services/android/navigation/v5/navigation/NavigationTelemetry.java
index e5a23e059ec..8634835e999 100644
--- a/libandroid-navigation/src/main/java/com/mapbox/services/android/navigation/v5/navigation/NavigationTelemetry.java
+++ b/libandroid-navigation/src/main/java/com/mapbox/services/android/navigation/v5/navigation/NavigationTelemetry.java
@@ -6,7 +6,6 @@
import android.support.annotation.NonNull;
import com.mapbox.android.core.location.LocationEngine;
-import com.mapbox.android.core.location.LocationEngineListener;
import com.mapbox.android.telemetry.Event;
import com.mapbox.android.telemetry.TelemetryUtils;
import com.mapbox.api.directions.v5.models.DirectionsRoute;
@@ -34,7 +33,7 @@
import java.util.Locale;
import java.util.concurrent.TimeUnit;
-class NavigationTelemetry implements LocationEngineListener, NavigationMetricListener {
+class NavigationTelemetry implements NavigationMetricListener {
private Context context;
private static NavigationTelemetry instance;
@@ -46,15 +45,12 @@ class NavigationTelemetry implements LocationEngineListener, NavigationMetricLis
+ ".ReplayRouteLocationEngine";
private static final int TWENTY_SECOND_INTERVAL = 20;
- private List queuedRerouteEvents = new ArrayList<>();
- private List queuedFeedbackEvents = new ArrayList<>();
-
+ private final List queuedRerouteEvents = new ArrayList<>();
+ private final List queuedFeedbackEvents = new ArrayList<>();
private MetricsRouteProgress metricProgress;
private MetricsLocation metricLocation;
-
private NavigationEventDispatcher eventDispatcher;
private NavigationLifecycleMonitor lifecycleMonitor;
- private LocationEngine navigationLocationEngine;
private SessionState navigationSessionState;
private RingBuffer locationBuffer;
private Date lastRerouteDate;
@@ -82,16 +78,6 @@ public static synchronized NavigationTelemetry getInstance() {
return instance;
}
- @Override
- public void onConnected() {
- // No-op
- }
-
- @Override
- public void onLocationChanged(Location location) {
- updateCurrentLocation(location);
- }
-
@Override
public void onRouteProgressUpdate(RouteProgress routeProgress) {
this.metricProgress = new MetricsRouteProgress(routeProgress);
@@ -132,7 +118,7 @@ public void onArrival(RouteProgress routeProgress) {
void initialize(@NonNull Context context, @NonNull String accessToken,
MapboxNavigation navigation, LocationEngine locationEngine) {
if (!isInitialized) {
- updateLocationEngine(locationEngine);
+ updateLocationEngineName(locationEngine);
validateAccessToken(accessToken);
this.context = context;
@@ -240,27 +226,21 @@ void updateSessionRoute(DirectionsRoute directionsRoute) {
/**
* Called during {@link NavigationTelemetry#initialize(Context, String, MapboxNavigation, LocationEngine)}
* and any time {@link MapboxNavigation} gets an updated location engine.
- *
- * Removes the current location engine listener if it exists, then
- * sets up the new one / updates the location engine name.
- *
- * @param locationEngine to be used to update
*/
- void updateLocationEngine(LocationEngine locationEngine) {
- // Remove listener from previous engine
- if (navigationLocationEngine != null) {
- navigationLocationEngine.removeLocationEngineListener(this);
- }
-
- // Store the new engine and setup a new listener
+ void updateLocationEngineName(LocationEngine locationEngine) {
if (locationEngine != null) {
- navigationLocationEngine = locationEngine;
- navigationLocationEngine.addLocationEngineListener(this);
String locationEngineName = locationEngine.getClass().getName();
navigationSessionState = navigationSessionState.toBuilder().locationEngineName(locationEngineName).build();
}
}
+ void updateLocation(Location location) {
+ metricLocation = new MetricsLocation(location);
+ locationBuffer.addLast(location);
+ checkRerouteQueue();
+ checkFeedbackQueue();
+ }
+
/**
* Creates a new {@link FeedbackEvent} and adds it to the queue
* of events to be sent.
@@ -341,16 +321,6 @@ private void flushEventQueues() {
}
}
- private void updateCurrentLocation(Location rawLocation) {
- metricLocation = new MetricsLocation(rawLocation);
- locationBuffer.addLast(rawLocation);
-
- // Check queued reroute events
- checkRerouteQueue();
- // Check queued feedback events
- checkFeedbackQueue();
- }
-
private void checkRerouteQueue() {
Iterator iterator = queuedRerouteEvents.listIterator();
while (iterator.hasNext()) {
diff --git a/libandroid-navigation/src/main/java/com/mapbox/services/android/navigation/v5/navigation/RouteProcessorBackgroundThread.java b/libandroid-navigation/src/main/java/com/mapbox/services/android/navigation/v5/navigation/RouteProcessorBackgroundThread.java
index 0427bcd1938..05924dd318d 100644
--- a/libandroid-navigation/src/main/java/com/mapbox/services/android/navigation/v5/navigation/RouteProcessorBackgroundThread.java
+++ b/libandroid-navigation/src/main/java/com/mapbox/services/android/navigation/v5/navigation/RouteProcessorBackgroundThread.java
@@ -50,7 +50,7 @@ public boolean quit() {
return super.quit();
}
- void updateRawLocation(Location rawLocation) {
+ void updateLocation(Location rawLocation) {
navigation.retrieveMapboxNavigator().updateLocation(rawLocation);
if (!isAlive()) {
start();
diff --git a/libandroid-navigation/src/test/java/com/mapbox/services/android/navigation/v5/location/replay/ReplayRouteLocationListenerTest.java b/libandroid-navigation/src/test/java/com/mapbox/services/android/navigation/v5/location/replay/ReplayRouteLocationListenerTest.java
new file mode 100644
index 00000000000..7b1d0b3a993
--- /dev/null
+++ b/libandroid-navigation/src/test/java/com/mapbox/services/android/navigation/v5/location/replay/ReplayRouteLocationListenerTest.java
@@ -0,0 +1,36 @@
+package com.mapbox.services.android.navigation.v5.location.replay;
+
+import android.location.Location;
+
+import com.mapbox.android.core.location.LocationEngineCallback;
+
+import org.junit.Test;
+
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.verify;
+
+public class ReplayRouteLocationListenerTest {
+
+ @Test
+ public void onLocationReplay_lastMockedLocationRemoved() {
+ ReplayRouteLocationEngine engine = mock(ReplayRouteLocationEngine.class);
+ LocationEngineCallback callback = mock(LocationEngineCallback.class);
+ ReplayRouteLocationListener listener = new ReplayRouteLocationListener(engine, callback);
+
+ listener.onLocationReplay(mock(Location.class));
+
+ verify(engine).removeLastMockedLocation();
+ }
+
+ @Test
+ public void onLocationReplay_updateLastLocation() {
+ ReplayRouteLocationEngine engine = mock(ReplayRouteLocationEngine.class);
+ LocationEngineCallback callback = mock(LocationEngineCallback.class);
+ Location location = mock(Location.class);
+ ReplayRouteLocationListener listener = new ReplayRouteLocationListener(engine, callback);
+
+ listener.onLocationReplay(location);
+
+ verify(engine).updateLastLocation(location);
+ }
+}
\ No newline at end of file
diff --git a/libandroid-navigation/src/test/java/com/mapbox/services/android/navigation/v5/navigation/LocationUpdaterTest.java b/libandroid-navigation/src/test/java/com/mapbox/services/android/navigation/v5/navigation/LocationUpdaterTest.java
new file mode 100644
index 00000000000..4cc6b71ea10
--- /dev/null
+++ b/libandroid-navigation/src/test/java/com/mapbox/services/android/navigation/v5/navigation/LocationUpdaterTest.java
@@ -0,0 +1,98 @@
+package com.mapbox.services.android.navigation.v5.navigation;
+
+import android.location.Location;
+import android.os.Looper;
+
+import com.mapbox.android.core.location.LocationEngine;
+import com.mapbox.android.core.location.LocationEngineCallback;
+import com.mapbox.android.core.location.LocationEngineRequest;
+import com.mapbox.android.core.location.LocationEngineResult;
+
+import org.junit.Test;
+
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+public class LocationUpdaterTest {
+
+ @Test
+ public void updateLocationEngine_previousUpdatesRemoved() {
+ RouteProcessorBackgroundThread thread = mock(RouteProcessorBackgroundThread.class);
+ LocationEngine locationEngine = mock(LocationEngine.class);
+ LocationEngineRequest locationEngineRequest = mock(LocationEngineRequest.class);
+ LocationUpdater locationUpdater = new LocationUpdater(thread, locationEngine, locationEngineRequest);
+
+ locationUpdater.updateLocationEngine(mock(LocationEngine.class));
+
+ verify(locationEngine).removeLocationUpdates(any(LocationEngineCallback.class));
+ }
+
+ @Test
+ public void updateLocationEngineRequest_previousUpdatesRemoved() {
+ RouteProcessorBackgroundThread thread = mock(RouteProcessorBackgroundThread.class);
+ LocationEngine locationEngine = mock(LocationEngine.class);
+ LocationEngineRequest locationEngineRequest = mock(LocationEngineRequest.class);
+ LocationUpdater locationUpdater = new LocationUpdater(thread, locationEngine, locationEngineRequest);
+
+ locationUpdater.updateLocationEngineRequest(mock(LocationEngineRequest.class));
+
+ verify(locationEngine).removeLocationUpdates(any(LocationEngineCallback.class));
+ }
+
+ @Test
+ public void removeLocationUpdates_updatesRemoved() {
+ RouteProcessorBackgroundThread thread = mock(RouteProcessorBackgroundThread.class);
+ LocationEngine locationEngine = mock(LocationEngine.class);
+ LocationEngineRequest locationEngineRequest = mock(LocationEngineRequest.class);
+ LocationUpdater locationUpdater = new LocationUpdater(thread, locationEngine, locationEngineRequest);
+
+ locationUpdater.removeLocationUpdates();
+
+ verify(locationEngine).removeLocationUpdates(any(LocationEngineCallback.class));
+ }
+
+ @Test
+ public void updateLocationEngine_newUpdatesRequested() {
+ RouteProcessorBackgroundThread thread = mock(RouteProcessorBackgroundThread.class);
+ LocationEngine locationEngine = mock(LocationEngine.class);
+ LocationEngineRequest locationEngineRequest = mock(LocationEngineRequest.class);
+ LocationUpdater locationUpdater = new LocationUpdater(thread, locationEngine, locationEngineRequest);
+
+ locationUpdater.updateLocationEngine(mock(LocationEngine.class));
+
+ verify(locationEngine).requestLocationUpdates(any(LocationEngineRequest.class),
+ any(LocationEngineCallback.class), eq((Looper) null));
+ }
+
+ @Test
+ public void updateLocationEngineRequest_newUpdatesRequested() {
+ RouteProcessorBackgroundThread thread = mock(RouteProcessorBackgroundThread.class);
+ LocationEngine locationEngine = mock(LocationEngine.class);
+ LocationEngineRequest locationEngineRequest = mock(LocationEngineRequest.class);
+ LocationUpdater locationUpdater = new LocationUpdater(thread, locationEngine, locationEngineRequest);
+
+ locationUpdater.updateLocationEngineRequest(mock(LocationEngineRequest.class));
+
+ verify(locationEngine, times(2)).requestLocationUpdates(any(LocationEngineRequest.class),
+ any(LocationEngineCallback.class), eq((Looper) null));
+ }
+
+ @Test
+ public void onSuccess_currentLocationEngineCallbackUpdatesCorrectly() {
+ LocationEngineResult result = mock(LocationEngineResult.class);
+ Location location = mock(Location.class);
+ when(result.getLastLocation()).thenReturn(location);
+ LocationUpdater locationUpdater = mock(LocationUpdater.class);
+ LocationUpdater.CurrentLocationEngineCallback callback = new LocationUpdater.CurrentLocationEngineCallback(
+ locationUpdater
+ );
+
+ callback.onSuccess(result);
+
+ verify(locationUpdater).onLocationChanged(location);
+ }
+}
\ No newline at end of file
diff --git a/libandroid-navigation/src/test/java/com/mapbox/services/android/navigation/v5/navigation/MapboxNavigationTest.java b/libandroid-navigation/src/test/java/com/mapbox/services/android/navigation/v5/navigation/MapboxNavigationTest.java
index 592d0d5459d..6747f96e10a 100644
--- a/libandroid-navigation/src/test/java/com/mapbox/services/android/navigation/v5/navigation/MapboxNavigationTest.java
+++ b/libandroid-navigation/src/test/java/com/mapbox/services/android/navigation/v5/navigation/MapboxNavigationTest.java
@@ -3,6 +3,7 @@
import android.content.Context;
import com.mapbox.android.core.location.LocationEngine;
+import com.mapbox.android.core.location.LocationEngineRequest;
import com.mapbox.api.directions.v5.models.DirectionsRoute;
import com.mapbox.services.android.navigation.v5.BaseTest;
import com.mapbox.services.android.navigation.v5.milestone.BannerInstructionMilestone;
@@ -308,6 +309,28 @@ public void updateRouteLegIndex_validIndexIsUpdated() throws IOException {
assertTrue(didUpdate);
}
+ @Test
+ public void updateLocationEngine_engineIsSet() {
+ LocationEngine locationEngine = mock(LocationEngine.class);
+ MapboxNavigation navigation = buildMapboxNavigationWith(locationEngine);
+ LocationEngine newLocationEngine = mock(LocationEngine.class);
+
+ navigation.setLocationEngine(newLocationEngine);
+
+ LocationEngine currentLocationEngine = navigation.getLocationEngine();
+ assertNotSame(locationEngine, currentLocationEngine);
+ }
+
+ @Test
+ public void defaultLocationEngineRequest_createdOnInitialization() {
+ LocationEngine locationEngine = mock(LocationEngine.class);
+ MapboxNavigation navigation = buildMapboxNavigationWith(locationEngine);
+
+ LocationEngineRequest request = navigation.retrieveLocationEngineRequest();
+
+ assertNotNull(request);
+ }
+
private MapboxNavigation buildMapboxNavigationWith(MapboxNavigator mapboxNavigator) {
Context context = mock(Context.class);
when(context.getApplicationContext()).thenReturn(context);
@@ -315,6 +338,13 @@ private MapboxNavigation buildMapboxNavigationWith(MapboxNavigator mapboxNavigat
mock(LocationEngine.class), mapboxNavigator);
}
+ private MapboxNavigation buildMapboxNavigationWith(LocationEngine locationEngine) {
+ Context context = mock(Context.class);
+ when(context.getApplicationContext()).thenReturn(context);
+ return new MapboxNavigation(context, ACCESS_TOKEN, mock(NavigationTelemetry.class),
+ locationEngine, mock(MapboxNavigator.class));
+ }
+
private MapboxNavigation buildMapboxNavigation() {
Context context = mock(Context.class);
when(context.getApplicationContext()).thenReturn(context);
diff --git a/libandroid-navigation/src/test/java/com/mapbox/services/android/navigation/v5/navigation/NavigationLocationEngineListenerTest.java b/libandroid-navigation/src/test/java/com/mapbox/services/android/navigation/v5/navigation/NavigationLocationEngineListenerTest.java
deleted file mode 100644
index 6a722618473..00000000000
--- a/libandroid-navigation/src/test/java/com/mapbox/services/android/navigation/v5/navigation/NavigationLocationEngineListenerTest.java
+++ /dev/null
@@ -1,73 +0,0 @@
-package com.mapbox.services.android.navigation.v5.navigation;
-
-import android.location.Location;
-
-import com.mapbox.android.core.location.LocationEngine;
-
-import org.junit.Test;
-
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.verify;
-import static org.mockito.Mockito.verifyZeroInteractions;
-import static org.mockito.Mockito.when;
-
-public class NavigationLocationEngineListenerTest {
-
- @Test
- public void onConnected_engineRequestsUpdates() {
- LocationEngine locationEngine = mock(LocationEngine.class);
- NavigationLocationEngineListener listener = buildListener(locationEngine);
-
- listener.onConnected();
-
- verify(locationEngine).requestLocationUpdates();
- }
-
- @Test
- public void onConnected_nonNullLastLocationIsSent() {
- LocationEngine locationEngine = mock(LocationEngine.class);
- Location location = mock(Location.class);
- when(locationEngine.getLastLocation()).thenReturn(location);
- RouteProcessorBackgroundThread thread = mock(RouteProcessorBackgroundThread.class);
- NavigationLocationEngineListener listener = new NavigationLocationEngineListener(
- thread, locationEngine
- );
-
- listener.onConnected();
-
- verify(thread).updateRawLocation(location);
- }
-
- @Test
- public void onConnected_nullLastLocationIsIgnored() {
- LocationEngine locationEngine = mock(LocationEngine.class);
- when(locationEngine.getLastLocation()).thenReturn(null);
- RouteProcessorBackgroundThread thread = mock(RouteProcessorBackgroundThread.class);
- NavigationLocationEngineListener listener = new NavigationLocationEngineListener(
- thread, locationEngine
- );
-
- listener.onConnected();
-
- verifyZeroInteractions(thread);
- }
-
- @Test
- public void queueValidLocationUpdate_threadReceivesUpdate() {
- RouteProcessorBackgroundThread thread = mock(RouteProcessorBackgroundThread.class);
- NavigationLocationEngineListener listener = buildListener(thread);
- Location location = mock(Location.class);
-
- listener.onLocationChanged(location);
-
- verify(thread).updateRawLocation(location);
- }
-
- private NavigationLocationEngineListener buildListener(RouteProcessorBackgroundThread thread) {
- return new NavigationLocationEngineListener(thread, mock(LocationEngine.class));
- }
-
- private NavigationLocationEngineListener buildListener(LocationEngine locationEngine) {
- return new NavigationLocationEngineListener(mock(RouteProcessorBackgroundThread.class), locationEngine);
- }
-}
\ No newline at end of file
diff --git a/libandroid-navigation/src/test/java/com/mapbox/services/android/navigation/v5/navigation/NavigationLocationEngineUpdaterTest.java b/libandroid-navigation/src/test/java/com/mapbox/services/android/navigation/v5/navigation/NavigationLocationEngineUpdaterTest.java
deleted file mode 100644
index 0f7a9d0f741..00000000000
--- a/libandroid-navigation/src/test/java/com/mapbox/services/android/navigation/v5/navigation/NavigationLocationEngineUpdaterTest.java
+++ /dev/null
@@ -1,57 +0,0 @@
-package com.mapbox.services.android.navigation.v5.navigation;
-
-import com.mapbox.android.core.location.LocationEngine;
-
-import org.junit.Test;
-
-import static org.mockito.ArgumentMatchers.eq;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.verify;
-
-public class NavigationLocationEngineUpdaterTest {
-
- @Test
- public void onInitialization_engineListenerIsSet() {
- LocationEngine locationEngine = mock(LocationEngine.class);
- NavigationLocationEngineListener listener = mock(NavigationLocationEngineListener.class);
-
- new NavigationLocationEngineUpdater(locationEngine, listener);
-
- verify(locationEngine).addLocationEngineListener(eq(listener));
- }
-
- @Test
- public void updateLocationEngine_engineListenerIsAdded() {
- LocationEngine locationEngine = mock(LocationEngine.class);
- NavigationLocationEngineListener listener = mock(NavigationLocationEngineListener.class);
- NavigationLocationEngineUpdater provider = new NavigationLocationEngineUpdater(locationEngine, listener);
- LocationEngine newLocationEngine = mock(LocationEngine.class);
-
- provider.updateLocationEngine(newLocationEngine);
-
- verify(newLocationEngine).addLocationEngineListener(eq(listener));
- }
-
- @Test
- public void updateLocationEngine_oldEngineListenerIsRemoved() {
- LocationEngine locationEngine = mock(LocationEngine.class);
- NavigationLocationEngineListener listener = mock(NavigationLocationEngineListener.class);
- NavigationLocationEngineUpdater provider = new NavigationLocationEngineUpdater(locationEngine, listener);
- LocationEngine newLocationEngine = mock(LocationEngine.class);
-
- provider.updateLocationEngine(newLocationEngine);
-
- verify(locationEngine).removeLocationEngineListener(eq(listener));
- }
-
- @Test
- public void removeLocationEngineListener() {
- LocationEngine locationEngine = mock(LocationEngine.class);
- NavigationLocationEngineListener listener = mock(NavigationLocationEngineListener.class);
- NavigationLocationEngineUpdater provider = new NavigationLocationEngineUpdater(locationEngine, listener);
-
- provider.removeLocationEngineListener();
-
- verify(locationEngine).removeLocationEngineListener(eq(listener));
- }
-}
\ No newline at end of file