Mapbox Navigation SDK for Android

repository·main·Indexed 20 days ago

https://github.com/mapbox/mapbox-navigation-android

SDK for integrating turn-by-turn navigation, routing, and location services into Android applications. Includes specialized support for Android Auto via the android-auto-components dependency, featuring MapboxCarMap, MapboxNavigationApp, and MapboxCarContext for managing head unit experiences, maneuver icon customization, and Jetpack Car Library integration.

Tokens
13K
Snippets
42
Records
53
Agent score
70%

What's inside mapbox-navigation-android

  1. Understand spoken instruction delivery (Voice API vs TextToSpeech)

    main

    The SDK uses two methods to announce instructions:

    1. Mapbox Voice API: The default method. It is powered by Amazon Polly and provides high-quality speech but requires an internet connection.
    2. TextToSpeech (TTS): Used as a fallback if the Mapbox Voice API lacks support for the requested language or if there is no internet connection.

    Note on Device Support: For certain languages (like Burmese, Chinese, Finnish, etc.), the SDK relies on the device's local TextToSpeech engine. The SDK cannot guarantee that a specific device will have the necessary third-party speech engine installed to pronounce these instructions correctly.

  2. How to replay locations with MapboxReplayer

    main

    The ReplayLocationEngine has been replaced by ReplayLocationProvider. To replay a trip session, use the mapboxReplayer instance created by the MapboxNavigation instance and call startReplayTripSession() instead of startTripSession().

    // Use the mapboxReplayer instance that NavSDK created for you:
    val mapboxReplayer = mapboxNavigation.mapboxReplayer
    
    // ...
    
    // This tells NavSDK to start using mapboxReplayer instead of the real location engine
    mapboxNavigation.startReplayTripSession()
  3. Understand Mapbox SDK resource naming conventions

    main

    To prevent resource name collisions with your own application, the Mapbox Navigation SDK prefixes all its resource files with mapbox_ or Mapbox. When inspecting the SDK's resources or attempting to override them, follow these naming patterns:

    • Drawables: mapbox_<bg/ic/drawable>_<function/feature name>[_state].xml
    • Layouts: mapbox[_view-type]_<function/feature name>_layout.xml
    • Animations: mapbox_animation_<function/feature name>.xml
    • Styles: Always start with MapboxStyle (e.g., MapboxStyleNavigationMapRoute)
    • Colors/Dimens/Strings: Always start with mapbox_ (e.g., mapbox_primary_maneuver_text_color)
  4. How Mapbox Android Auto components work together

    main

    The SDK provides building blocks to implement the Android Auto experience within your MainCarSession.

    • MapboxCarMap: Used to display the Mapbox Map on the Android Auto head unit. You can manage map elements using MapboxCarMapObserver.
    • MapboxNavigationApp: Used to customize the turn-by-turn navigation experience.

    These components work together to bridge Mapbox's core capabilities (Maps, Navigation, and Search) with the Jetpack Car Library requirements.

  5. Test Android Auto using the Desktop Head Unit (DHU) Emulator

    main

    Testing Android Auto requires an emulator and the Android Auto Desktop Head Unit (DHU).

    1. Install DHU: Use the Android SDK Manager to install 'Android Auto Desktop Head Unit Emulator'.
    2. Setup Phone: Ensure the Android Auto app is installed on your device. Enable developer settings in the Android Auto app (tap device info/version info), then select 'Start head unit server' from the menu.
    3. Environment: Set the ANDROID_HOME environment variable to your Android SDK location.
    4. Run: Use the provided make command and execute the DHU binary.
    # Set ANDROID_HOME first
    $ make car
       $ adb forward tcp:5277 tcp:5277
       $ cd $(ANDROID_HOME)/extras/google/auto/
       $ ./desktop-head-unit
  6. Configure measurement units for spoken instructions

    main

    By default, distances in spoken instructions use the predominant measurement system of the system region. To override this and specify a different measurement system (e.g., switching between metric and imperial), set the unitType property on the MapboxNavigationOptions.Builder when calculating the route.

    // Example of overriding the measurement system
    val options = MapboxNavigationOptions.Builder()
        .unitType(UnitType.IMPERIAL) // Or UnitType.METRIC
        // ... other builder methods
        .build()
  7. Setup test routes using CustomRouterRule

    main

    To mock online routes in instrumentation tests, use CustomRouterRule instead of implementing a custom Router. This intercepts requests to the Mapbox Directions API.

    1. Add the dependency: androidTestImplementation(com.mapbox.navigationcore:testing-router:${navigation_core_version}).
    2. Add the rule to your test class.
    3. Implement MapboxNavigationTestRouter and MapboxNavigationTestRouteRefresher to provide mock responses.
    @get:Rule
    val navigationRouterRule = createNavigationRouterRule()
    
    navigationRouterRule.setRouter(object : MapboxNavigationTestRouter {
        override fun getRoute(routeOptions: RouteOptions, callback: RouterCallback) {
            if (routeOptions == testRouteOptions) {
                callback.onRoutesReady(mockRoute.routeResponse)
            } else {
                callback.onFailure(TestRouterFailure.noRoutesFound())
            }
        }
    })
    
    navigationRouterRule.setRouteRefresher(object : MapboxNavigationTestRouteRefresher {
        override fun getRouteRefresh(options: RefreshOptions, callback: RouteRefreshCallback) {
            if (options.responseUUID == mockRoute.routeResponse.uuid()) {
                callback.onRefresh(mockRoute.routeResponse.routes()[options.routeIndex])
            } else {
                callback.onFailure(TestRefresherFailure.serverError())
            }
        }
    })
  8. Download tileset_helsinki.zip for coordination tests

    main

    To run coordination tests that require the Helsinki tileset, you must download tileset_helsinki.zip from S3 to your local assets directory.

    If you are working from the navigation/projects/mapbox-navigation-internal directory, use the specific target path provided below. This file is ignored by git, so you can keep it locally without committing it.

    # 1. Install AWS CLI (macOS)
    brew install awscli
    
    # 2. Set up Mapbox environment
    mbx env
    
    # 3. Download the tileset to the assets directory
    aws s3 cp "s3://mapbox-navigation-android/testing/tileset_helsinki.zip" mapbox-navigation-android/libtesting-resources/src/main/assets
  9. Configure AndroidManifest for Android Auto Navigation

    main

    To be accepted by Google Play as a navigation app, you must declare a CarAppService in your AndroidManifest.xml and include the androidx.car.app.category.NAVIGATION category within an <intent-filter>. The service must also specify android:foregroundServiceType="location".

    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        package="com.mapbox.navigation.testapp">
    
        <application
            <!-- Link to your implementation of CarAppService -->
            <service
                android:name=".car.MainCarAppService"
                android:exported="true"
                tools:ignore="ExportedService"
                android:foregroundServiceType="location">
    
                <intent-filter>
                    <action android:name="androidx.car.app.CarAppService" />
                    <category android:name="androidx.car.app.category.NAVIGATION" />
                </intent-filter>
            </service>
        </application>
    </manifest>
  10. Configure Ktlint for code style enforcement

    main

    The project uses Ktlint to enforce Kotlin code style. To set it up manually on Mac OS or Linux:

    1. Install Ktlint via Homebrew: brew install ktlint
    2. Apply the configuration to your IntelliJ IDEA project from the project's root directory: ktlint --android applyToIDEAProject

    Note: The current root directory is mapbox-navigation-android.

    brew install ktlint
    ktlint --android applyToIDEAProject
  11. Configure Android Studio Checkstyle

    main

    To ensure Android Studio adheres to the Mapbox Java code style, import the provided XML scheme:

    1. Open Android Studio -> Preferences.
    2. Navigate to Code Style.
    3. Click the Settings Icon (gear icon) and select Import Scheme -> IntelliJ IDEA code style XML.
    4. Select the mapbox-java-codestyle.xml file and click Open.
    5. Ensure the checkbox for the imported scheme is selected and click OK.