Guía de migración del SDK de Android Driver 3.0

Para la versión 3.0 del SDK de Driver para Android, debes actualizar el código. para ciertas operaciones. En esta guía, se describen los cambios que debes hacer para migrar tu código.

Cambio de nombre de paquete

El nombre del paquete cambió de com.google.android.libraries.ridesharing.driver a com.google.android.libraries.mapsplatform.transportation.driver Por favor, actualizar las referencias en tu código.

Inicializa el SDK

En versiones anteriores, inicializabas el SDK de Navigation y, luego, obtenías una referencia a la clase FleetEngine. En el SDK de Driver v3, inicializa el SDK de la siguiente manera:

  1. Obtén un objeto Navigator de NavigationApi.

    NavigationApi.getNavigator(
          this, // Activity
          new NavigationApi.NavigatorListener() {
            @Override
            public void onNavigatorReady(Navigator navigator) {
              // Keep a reference to the Navigator (used to configure and start nav)
              this.navigator = navigator;
            }
          }
    );
    
  2. Crea un objeto DriverContext y propaga los campos obligatorios.

    DriverContext driverContext = DriverContext.builder(application)
                 .setProviderId(providerId)
                 .setVehicleId(vehicleId)
                 .setAuthTokenFactory(authTokenFactory)
                 .setNavigator(navigator)
                 .setRoadSnappedLocationProvider(
                     NavigationApi.getRoadSnappedLocationProvider(application))
                 .build()
    
  3. Usa el objeto DriverContext para inicializar *DriverApi.

    RidesharingDriverApi ridesharingDriverApi = RidesharingDriverApi.createInstance(driverContext);
    
  4. Obtén el NavigationVehicleReporter del objeto de la API. *VehicleReporter extiende NavigationVehicleReporter.

    RidesharingVehicleReporter vehicleReporter = ridesharingDriverApi.getRidesharingVehicleReporter();
    

Cómo habilitar o inhabilitar las actualizaciones de ubicación

En versiones anteriores, habilitabas las actualizaciones de ubicación después de obtener Una referencia FleetEngine En la versión 3 del SDK de Driver, habilita ubicación se actualiza de la siguiente manera:

RidesharingVehicleReporter reporter = ...;

reporter.enableLocationTracking();

Para actualizar el intervalo del informe, usa RidesharingVehicleReporter.setLocationReportingInterval(long, TimeUnit) o DeliveryVehicleReporter.setLocationReportingInterval(long, TimeUnit)

Cuando termine el turno del conductor, inhabilitar las actualizaciones de ubicación y marca el vehículo como sin conexión llamando a NavigationVehicleReporter.disableLocationTracking().

Configura el estado del vehículo en el servidor

En versiones anteriores, se usaba el objeto FleetEngine para configurar el estado del vehículo. En la versión 3 del SDK de Driver, usa la RidesharingVehicleReporter para establecer el estado del vehículo:

  RidesharingVehicleReporter reporter = ...;

  reporter.enableLocationTracking();
  reporter.setVehicleState(VehicleState.ONLINE);

Para establecer el estado del vehículo en OFFLINE, llama a RidesharingVehicleReporter.disableLocationTracking() Errores la actualización del estado del vehículo se propagan con los recursos StatusListener se establece en DriverContext.

Error Reporting con StatusListener

Se quitó ErrorListener y se combinó con StatusListener, que se puede definir de la siguiente manera:

class MyStatusListener implements StatusListener {
  /** Called when background status is updated, during actions such as location reporting. */
  @Override
  public void updateStatus(
    StatusLevel statusLevel,
    StatusCode statusCode,
    String statusMsg) {
    // Status handling stuff goes here.
    // StatusLevel may be DEBUG, INFO, WARNING, or ERROR.
    // StatusCode may be DEFAULT, UNKNOWN_ERROR, VEHICLE_NOT_FOUND, 
    // BACKEND_CONNECTIVITY_ERROR, or PERMISSION_DENIED.
  }
}

Autentica con AuthTokenFactory

AuthTokenFactory ahora solo tiene un método, getToken(), que recibe un AuthTokenContext como parámetro. Los clientes de transporte compartido deben autenticarse para el tipo de servicio VEHICLE, que habilita la ubicación informes y de estado del vehículo (en línea/sin conexión).

class JsonAuthTokenFactory implements AuthTokenFactory {
  String vehicleServiceToken;  // initially null
  long expiryTimeMs = 0;

  // This method is called on a thread whose only responsibility is to send
  // location updates. Blocking is OK, but just know that no location updates
  // can occur until this method returns.
  @Override public String getToken(AuthTokenContext authTokenContext) {
    if (System.currentTimeMillis() > expiryTimeMs) {
      // The token has expired, go get a new one.
      fetchNewToken(vehicleId);
    }
    if (ServiceType.VEHICLE.equals(authTokenContext.getServiceType)) {
      return vehicleServiceToken;
    } else {
      throw new RuntimeException("Unsupported ServiceType: " + authTokenContext.getServiceType());
    }
  }

  private void fetchNewToken(String vehicleId) {
    String url = "https://yourauthserver.example/token/" + vehicleId;

    try (Reader r = new URL(url).openStream()) {
      com.google.gson.JsonObject obj
          = new com.google.gson.JsonParser().parse(r);
      vehicleServiceToken = obj.get("VehicleServiceToken").getAsString();
      expiryTimeMs = obj.getAsLong("TokenExpiryMs");

      // The expiry time could be an hour from now, but just to try and avoid
      // passing expired tokens, we subtract 10 minutes from that time.
      expiryTimeMs -= 10 * 60 * 1000;
    } catch (IOException e) {
      // It's OK to throw exceptions here, the StatusListener you passed to
      // create the FleetEngine class will be notified and pass along the failed
      // update warning.
      throw new RuntimeException("Could not get auth token", e);
    }
  }
}