Configura una sesión de ARCore en Android

Configura una sesión de ARCore para crear experiencias de RA para tu app.

¿Qué es una sesión?

Todos los procesos de RA, como el seguimiento de movimiento, la comprensión del entorno y la estimación de la iluminación, se ejecutan dentro de una sesión de ARCore. Session es el punto de entrada principal a la API de ARCore. Administra el estado del sistema de RA y controla el ciclo de vida de la sesión, lo que permite que la app cree, configure, inicie o detenga una sesión. Lo más importante es que habilita la app para recibir fotogramas que permiten el acceso a la imagen de la cámara y a la posición del dispositivo.

La sesión se puede usar para configurar las siguientes funciones:

Verifica que ARCore esté instalado y actualizado

Antes de crear un Session, verifica que ARCore esté instalado y actualizado. Si ARCore no está instalado, falla la creación de la sesión y cualquier instalación o actualización posterior de ARCore requiere que se reinicie la app.

Java

// Verify that ARCore is installed and using the current version.
private boolean isARCoreSupportedAndUpToDate() {
  ArCoreApk.Availability availability = ArCoreApk.getInstance().checkAvailability(this);
  switch (availability) {
    case SUPPORTED_INSTALLED:
      return true;

    case SUPPORTED_APK_TOO_OLD:
    case SUPPORTED_NOT_INSTALLED:
      try {
        // Request ARCore installation or update if needed.
        ArCoreApk.InstallStatus installStatus = ArCoreApk.getInstance().requestInstall(this, true);
        switch (installStatus) {
          case INSTALL_REQUESTED:
            Log.i(TAG, "ARCore installation requested.");
            return false;
          case INSTALLED:
            return true;
        }
      } catch (UnavailableException e) {
        Log.e(TAG, "ARCore not installed", e);
      }
      return false;

    case UNSUPPORTED_DEVICE_NOT_CAPABLE:
      // This device is not supported for AR.
      return false;

    case UNKNOWN_CHECKING:
      // ARCore is checking the availability with a remote query.
      // This function should be called again after waiting 200 ms to determine the query result.
    case UNKNOWN_ERROR:
    case UNKNOWN_TIMED_OUT:
      // There was an error checking for AR availability. This may be due to the device being offline.
      // Handle the error appropriately.
  }
}

Kotlin

// Verify that ARCore is installed and using the current version.
fun isARCoreSupportedAndUpToDate(): Boolean {
  return when (ArCoreApk.getInstance().checkAvailability(this)) {
    Availability.SUPPORTED_INSTALLED -> true
    Availability.SUPPORTED_APK_TOO_OLD, Availability.SUPPORTED_NOT_INSTALLED -> {
      try {
        // Request ARCore installation or update if needed.
        when (ArCoreApk.getInstance().requestInstall(this, true)) {
          InstallStatus.INSTALL_REQUESTED -> {
            Log.i(TAG, "ARCore installation requested.")
            false
          }
          InstallStatus.INSTALLED -> true
        }
      } catch (e: UnavailableException) {
        Log.e(TAG, "ARCore not installed", e)
        false
      }
    }

    Availability.UNSUPPORTED_DEVICE_NOT_CAPABLE ->
      // This device is not supported for AR.
      false

    Availability.UNKNOWN_CHECKING -> {
      // ARCore is checking the availability with a remote query.
      // This function should be called again after waiting 200 ms to determine the query result.
    }
    Availability.UNKNOWN_ERROR, Availability.UNKNOWN_TIMED_OUT -> {
      // There was an error checking for AR availability. This may be due to the device being offline.
      // Handle the error appropriately.
    }
  }
}

Crea una sesión

Crea y configura una sesión en ARCore.

Java

public void createSession() {
  // Create a new ARCore session.
  session = new Session(this);

  // Create a session config.
  Config config = new Config(session);

  // Do feature-specific operations here, such as enabling depth or turning on
  // support for Augmented Faces.

  // Configure the session.
  session.configure(config);
}

Kotlin

fun createSession() {
  // Create a new ARCore session.
  session = Session(this)

  // Create a session config.
  val config = Config(session)

  // Do feature-specific operations here, such as enabling depth or turning on
  // support for Augmented Faces.

  // Configure the session.
  session.configure(config)
}

Cómo cerrar una sesión

Session posee una cantidad significativa de memoria del montón nativa. Si no cierras la sesión de forma explícita, es posible que tu app se quede sin memoria nativa y falle. Cuando ya no se necesite la sesión de RA, llama a close() para liberar recursos. Si tu app contiene una sola actividad habilitada para RA, llama a close() desde el método onDestroy() de la actividad.

Java

// Release native heap memory used by an ARCore session.
session.close();

Kotlin

// Release native heap memory used by an ARCore session.
session.close()

Próximos pasos