El SDK de Driver para Android 4.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.
Para el modelo de controlador untrusted, los clientes de entregas solo deben autenticarse para el tipo de servicioVEHICLE
, lo que habilita los informes de ubicación. Los clientes con un modelo de controlador de confianza deben proporcionar autenticación para el tipo de servicio TASK
a fin de habilitar los métodos de informes de paradas de vehículos en DeliveryVehicleReporter
.
Cambio de nombre del 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 4 del SDK de Driver, inicializa el SDK como se indica a continuación:
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
.DeliveryDriverApi deliveryDriverApi = DeliveryDriverApi.createInstance(driverContext);
Obtén el
NavigationVehicleReporter
del objeto de la API.*VehicleReporter
extiendeNavigationVehicleReporter
.DeliveryVehicleReporter vehicleReporter = deliveryDriverApi.getDeliveryVehicleReporter();
Cómo habilitar e inhabilitar actualizaciones de ubicación
En versiones anteriores, habilitabas las actualizaciones de ubicación después de obtener una referencia FleetEngine
. En la versión 4 del SDK de Driver, habilita las actualizaciones de ubicación de la siguiente manera:
DeliveryVehicleReporter reporter = ...;
reporter.enableLocationTracking();
Para actualizar el intervalo de informes, usa 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()
.
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.
}
}
Autenticando con AuthTokenFactory
AuthTokenFactory
ahora tiene un solo método, getToken()
, que toma AuthTokenContext
como parámetro.
class JsonAuthTokenFactory implements AuthTokenFactory {
// Initially null.
private String vehicleServiceToken;
// Initially null. Only used in the trusted driver model to authenticate
// vehicle-stop reporting.
private String taskServiceToken;
private long expiryTimeMs = 0;
// This method is called on a thread that only sends location updates (and
// vehicle stop updates if you choose to report them). Blocking is OK, but just
// know that no 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 if (ServiceType.TASK.equals(authTokenContext.getServiceType())) {
// Only used for the trusted driver model to access vehicle-stop reporting
// methods in DeliveryVehicleReporter.
return taskServiceToken;
} else {
throw new RuntimeException("Unsupported ServiceType: " + authTokenContext.getServiceType());
}
}
private void fetchNewToken(String vehicleId) {
String url = "https://yourauthserver.example/token/" + vehicleId;
try (Reader r = new InputStreamReader(new URL(url).openStream())) {
com.google.gson.JsonObject obj
= com.google.gson.JsonParser.parseReader(r).getAsJsonObject();
vehicleServiceToken = obj.get("VehicleServiceToken").getAsString();
taskServiceToken = obj.get("TaskServiceToken").getAsString();
expiryTimeMs = obj.get("TokenExpiryMs").getAsLong();
// 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 DriverContext class will be notified and passed along the failed
// update warning.
throw new RuntimeException("Could not get auth token", e);
}
}
}
La lista Task
se convierte en lista TaskInfo
Se reemplazó la lista Task
por la lista TaskInfo
en VehicleStop
. En el siguiente ejemplo de código, se muestra cómo crear un objeto VehicleStop
.
VehicleStop vehicleStop = VehicleStop.builder()
.setTaskInfoList(taskInfoList)
.setWaypoint(waypoint)
.setVehicleStopState(vehicleStopState)
.build();