La versión del SDK de Driver para Android 3.0 requiere que actualices el código para ciertas operaciones. En esta guía, se describen los cambios y lo que deberás 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
. Actualiza 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 la versión 3 del SDK del controlador, inicializa el SDK de la siguiente manera:
Obtén un objeto
Navigator
deNavigationApi
.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; } } );
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()
Usa el objeto
DriverContext
para inicializar*DriverApi
.RidesharingDriverApi ridesharingDriverApi = RidesharingDriverApi.createInstance(driverContext);
Obtén el
NavigationVehicleReporter
del objeto de la API.*VehicleReporter
extiendeNavigationVehicleReporter
.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 de FleetEngine
. En la versión 3 del SDK del controlador, habilita las actualizaciones de ubicación 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 finalice el turno del conductor, inhabilita 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 establecer el estado del vehículo. En la versión 3 del SDK del controlador, usa el objeto 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()
. Los errores que actualizan el estado del vehículo se propagan con el objeto StatusListener
proporcionado de forma opcional en DriverContext
.
Error Reporting con StatusListener
Se quitó ErrorListener
y se combinó con StatusListener
, que puede definirse 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 toma un AuthTokenContext
como parámetro. Los clientes de transporte compartido deben autenticarse para el tipo de servicio VEHICLE
, que habilita los informes de ubicación y los informes del estado del vehículo (en línea y 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);
}
}
}