Android Driver SDK 4.0 이전 가이드

Android용 Driver SDK 4.0 출시에서는 특정 작업의 코드를 업데이트해야 합니다. 이 가이드에서는 변경사항과 코드를 이전하기 위해 수행해야 하는 작업을 간략히 설명합니다.

패키지 이름 변경

패키지 이름이 com.google.android.libraries.ridesharing.driver에서 com.google.android.libraries.mapsplatform.transportation.driver로 변경되었습니다. 코드에서 참조를 업데이트하세요.

SDK 초기화

이전 버전에서는 Navigation SDK를 초기화한 다음 FleetEngine 클래스 참조를 얻었습니다. 드라이버 SDK v4에서 다음과 같이 SDK를 초기화합니다.

  1. NavigationApi에서 Navigator 객체를 가져옵니다.

    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. DriverContext 객체를 만들고 필수 필드를 채웁니다.

    DriverContext driverContext = DriverContext.builder(application)
        .setProviderId(providerId)
        .setVehicleId(vehicleId)
        .setAuthTokenFactory(authTokenFactory)
        .setNavigator(navigator)
        .setRoadSnappedLocationProvider(
            NavigationApi.getRoadSnappedLocationProvider(application))
        .build();
    
  3. DriverContext 객체를 사용하여 *DriverApi를 초기화합니다.

    RidesharingDriverApi ridesharingDriverApi = RidesharingDriverApi.createInstance(driverContext);
    
  4. API 객체에서 NavigationVehicleReporter를 가져옵니다. *VehicleReporterNavigationVehicleReporter를 확장합니다.

    RidesharingVehicleReporter vehicleReporter = ridesharingDriverApi.getRidesharingVehicleReporter();
    

위치 업데이트 사용 설정 및 중지

이전 버전에서는 FleetEngine 참조를 얻은 후 위치 업데이트를 사용 설정했습니다. Driver SDK v4에서는 다음과 같이 위치 업데이트를 사용 설정합니다.

RidesharingVehicleReporter reporter = ...;

reporter.enableLocationTracking();

보고 간격을 업데이트하려면 RidesharingVehicleReporter.setLocationReportingInterval(long, TimeUnit)를 사용합니다.

운전자의 시프트가 완료되면 NavigationVehicleReporter.disableLocationTracking()를 호출하여 위치 업데이트를 사용 중지하고 차량을 오프라인 상태로 표시합니다.

서버에서 차량 상태 설정

이전 버전에서는 FleetEngine 객체를 사용하여 차량 상태를 설정했습니다. Driver SDK v4에서는 RidesharingVehicleReporter 객체를 사용하여 차량 상태를 설정합니다.

RidesharingVehicleReporter reporter = ...;

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

차량 상태를 OFFLINE로 설정하려면 RidesharingVehicleReporter.disableLocationTracking()를 호출합니다. 차량 상태를 업데이트하는 오류는 DriverContext에 설정된 선택사항으로 제공되는 StatusListener를 사용하여 전파됩니다.

StatusListener를 사용한 오류 보고

ErrorListener가 삭제되고 다음과 같이 정의될 수 있는 StatusListener와 결합되었습니다.

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.
  }
}

AuthTokenFactory로 인증

이제 AuthTokenFactory에는 AuthTokenContext를 매개변수로 사용하는 getToken() 메서드 하나만 있습니다. ServiceType가 지원 중단되었습니다. 이제 ServiceType에 의존하는 대신 포함된 차량 ID에 관한 클레임만 받으면 됩니다.

class JsonAuthTokenFactory implements AuthTokenFactory {
  private String token;  // initially null
  private 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(authTokenContext.getVehicleId());
    }
    return token;
  }

  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();
      token = obj.get("Token").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 is notified, and passes along the failed
      // update warning.
      throw new RuntimeException("Could not get auth token", e);
    }
  }
}