Skip to main content

Android APIs

Permissions

Before using any Spectacles Mobile Kit features, your app must explicitly request BLUETOOTH_CONNECT and BLUETOOTH_SCAN permissions from the user.

SpectaclesKit

The main entry point for working with the Spectacles Mobile Kit. It manages bonding and session setup between your app and Spectacles.

interface SpectaclesKit

Methods

bind
fun bind(
request: BondingRequest,
onResult: Consumer<BondingResult>
): Closable

Initiates a secure bonding process with the Lens specified in the provided BondingRequest.

Parameters
requestIdentifies the Lens to bind with.
onResultCallback to receive the bonding result.
Return
ClosableRepresents the ongoing bonding process. Call close() to cancel it if needed.
unbind
fun unbind(
id: String,
onResult: Consumer<UnbindingResult>,
graceful: Boolean = true
): Closable

Ends an existing secure bonding with a Lens.

Parameters
idThe ID of the bonding to revoke.
onResultCallback to receive the unbinding result.
gracefulWhether to unbind gracefully. Default is true
Return
ClosableRepresents the ongoing unbinding process. Call close() to cancel it if needed.
avaliableBondings
fun avaliableBondings(): List<Bonding>

Returns all available bondings.

Return
List<Bonding>A list of existing bondings.
getBonding
fun getBonding(id: String): Bonding?

Fetches the Bonding associated with the given id.

Parameters
idThe bonding ID.
Return
BondingThe bonding if found, or null if not available.
createSession
fun createSession(
bonding: Bonding,
request: SessionRequest,
delegateBuiler: (SpectaclesSession) -> SpectaclesRequestDelegate
): SpectaclesSession

Creates a session to communicate with the bounded Lens.

Parameters
bondingThe secure bonding to use.
requestThe session settings.
delegateBuilderFactory for creating a delegate to handle session requests.
Return
SpectaclesSessionThe created session

SpectaclesKit.Builder

Used to create a SpectaclesKit instance with required app credentials.

interface Builder

Methods

setIdentifier
fun setIdentifier(identifier: ClientIdentifier): Builder

Set the unique identifier for your application.

Parameters
identifierThe app’s client identifier
Return
BuilderFor chaining
setVersion
fun setVersion(version: String): Builder

Set the app version.

Parameters
versionThe app version
Return
BuilderFor chaining
setRequestExecutor
fun setRequestExecutor(executor: Executor): Builder

Sets the executor used to handle Lens requests.

Parameters
executorThe requests executor.
Return
BuilderFor chaining
build
fun build(): SpectaclesKit

Builds and returns a SpectaclesKit instance.

Return
SpectaclesKitThe SpectaclesKit instance.

newBuilder

Creates a SpectaclesKit.Builder with the provided context.

fun newBuilder(contex: Context): SpectaclesKit.Bulder
Parameters
contextAndroid context

SpectaclesKit.ClientIdentifier

Represents your app's unique identifier.

data class ClientIdentifier(val value: String)

Properties

value
val value: String

The client identifier.

SpectaclesKit.BondingRequest

Represents a request to initiate bonding with a specific Lens.

sealed class BondingRequest {
data class SingleLensByLensId(val lensId: String) : BondingRequest()
data class SingleLensByLensName(val lensName: String) : BondingRequest()
}

SpectaclesKit.BondingRequest.SingleLensByLensId

Request to bind with a Lens using its unique ID.

data class SingleLensByLensId(val lensId: String) : BondingRequest

Properties

lensId
val lensId: String

The unique identifier of the Lens to bind with.

SpectaclesKit.BondingRequest.SingleLensByLensName

Request to bind using a Lens's name.

Since names are not unique, this is for development use. Use SingleLensByLensId in production for better security.

When using this, make sure untrusted Lens connections are set to allowed — see SpectaclesKit.SessionRequest.Default for details.

data class SingleLensByLensName(val lensName: String) : BondingRequest

Properties

lensName
val lensName: String

The name of the Lens to bind with.

SpectaclesKit.BondingRequest

Represents the result of a bonding attempt.

sealed class BondingResult {
data class Success(val bonding: Bonding) : BondingResult()
data class Failure(val exception: Exception) : BondingResult()
}

SpectaclesKit.BondingRequest.Success

Indicates a successful bonding.

data class Success(val bonding: Bonding) : BondingResult

Properties

bonding
val bonding: Bonding

The resulting Bonding instance.

SpectaclesKit.BondingRequest.Failure

Indicates a bonding failure.

data class Failure(val exception: Exception) : BondingResult

Properties

exception
val exception: Exception

The exception that caused the failure.

SpectaclesKit.Bonding

Represents a secure bonding between the app and a Lens.

interface Bonding(val id: String)

Properties

id
val id: String

The unique ID of the bonding.

SpectaclesKit.UnbindingResult

Represents the result of an unbinding operation.

sealed class UnbindingResult {
data object Success : UnbindingResult()
data class Failure(val exception: Exception) : UnbindingResult()
}

SpectaclesKit.UnbindingResult.Success

Indicates a successful unbinding.

data object Success : UnbindingResult

SpectaclesKit.UnbindingResult.Failure

Indicates an unbinding failure.

data class Failure(val exception: Exception) : UnbindingResult

Properties

exception
val exception: Exception

The exception that caused the failure.

ClientException

Base class for exceptions related to SpectaclesKit client errors.

open class ClientException(
message: String,
cause: Exception? = null
) : Exception(message, cause) {
/**
* Exception thrown when the Lens SpectaclesKit is not installed.
*/
class LensClientNotInstalled(message: String) : ClientException(message)

/**
* Exception thrown when the specified device is not found.
*/
class DeviceNotFound(message: String): ClientException(message)

/**
* Exception thrown when the Spectacles app is not installed.
*/
class SpectaclesAppNotInstalled(message: String): ClientException(message)

/**
* Exception thrown when the Spectacles app is not enabled.
*/
class SpectaclesAppNotEnabled(message: String): ClientException(message)

/**
* Exception thrown when the Spectacles app needs to be updated.
*/
class SpectaclesAppUpdateRequired(message: String): ClientException(message)
}

SpectaclesKit.SessionRequest

Represents configuration options for establishing a session with Spectacles.

sealed abstract class SessionsRequest

Properties

autoReconnect
val autoReconnect: Boolean

If true, the session will try to reconnect automatically.

acceptUnfusedSpectacles
val acceptUnfusedSpectacles: Boolean

Allows connections to unfused (debug) Spectacles.

preSharedSecret
val preSharedSecret: Pair<ByteArray, ByteArray>?

Internal use only.

acceptUntrustedLens
val acceptUntrustedLens: Boolean

Allows untrusted Lens connections, useful for development with Lenses pushed from Lens Studio.

SpectaclesKit.SessionRequest.Default

A default implementation of SessionRequest with standard values.

data class Default(
override val autoReconnect: Boolean = true,
override val acceptUnfusedSpectacles: Boolean = false,
override val preShareSecret: Pair<ByteArray, ByteArray>? = null,
override val acceptUntrustedLens: Boolean = false
) : SessionRequest

SpectaclesSession

Represents an active session for connecting to and interacting with a specific Lens.

interface SpectaclesSession

Methods

observeConnectionstatus
fun observeConnectionStatus(onStatus: Consumer<ConnectionStatus>): Closable

Subscribes to connection status updates for the session.

Parameters
onStatusCallback that receives updates when the connection status changes.
Return
ClosableCall close() to unsubscribe from status updates.
connectionStatus
fun connectionStatus(): ConnectionStatus

Retrieves the current connection status of the session.

Return
ConnectionStatusThe current session state.
close
fun close(reason: ClonseReason?)

Closes the session and terminates the connection.

Parameters
reason(Optional) Reason for closing the session.

SpectaclesSession.CloseReason

Defines possible reasons for manually closing a session.

enum class CloseReason

Enum Values

Values
INCOMPATIBLE_LENSThe connected Lens is incompatible.

SpectaclesSession.DisconnectReason

Defines reasons for unexpected disconnection.

enum class DisconnectReason

Enum Values

Values
SESSION_CLOSEDThe session was explicitly closed by the caller.
CONNECTION_LOSTConnection was lost, likely due to network issues.

SpectaclesSession.ConnectionStatus

Represents the current state of the connection to a Lens.

sealed class ConnectionStatus {
object ConnectStart : ConnectionStatus()
data class Connected(val sessionMetadata: Metadata) : ConnectionStatus
data class Error(val exception: Exception) : ConnectionStatus
data class Disconnected(val reason: DisconnectReason) : ConnectionStatus
}

SpectaclesSession.ConnectionStatus.ConnectStart

Indicates the session is starting a connection.

object ConnectStart : ConnectionStatus

SpectaclesSession.ConnectionStatus.Connected

Connection successfully established.

data class Connected(val sessionMetadata: Metadata) : ConnectionStatus

Properties

sessionMetadata
val sessionMetadata: Metadata

The Metadata about the connected Lens.

SpectaclesSession.ConnectionStatus.Error

The connection attempt failed.

data class Error(val exception: Exception) : ConnectionStatus

Properties

exception
val exception: Exception

Provides the error details.

SpectaclesSession.ConnectionStatus.Disconnected

The session was disconnected.

data class Disconnected(val reason: DisconnectReason) : ConnectionStatus

Properties

exception
val reason: DisconnectReason

Explains the cause of disconnection.

SpectaclesSession.Metadata

Provides information about the connected Lens.

data class Metadata(
val lensId: String,
val lensVersion: String
)

Properties

lensId
val lensId: String

The unique identifier of the Lens.

lensVersion
val lensVersion: String

The version of the connected Lens.

SpectaclesRequestDelegate

Implement this interface to handle incoming requests from a connected Lens.

interface SpectaclesRequestDelegate

Methods

processServiceRequest
fun processServiceRequest(request: SpectaclesReqeust)

Invoked when the connected Lens sends a request.

Parameters
requestThe incoming SpectaclesRequest from the Lens that needs to be processed.

SpectaclesRequest

Base class for different types of Lens requests.

sealed interface SpectaclesRequest

SpectaclesRequest.WithoutResponse

Describes a request that does not expect a response (e.g., an event).

abstract class WithoutResponse : SpectaclesRequest

SpectaclesRequest.WithResponse

Represents a request that expects a single response (e.g., a one-time request).

abstract class WithResponse<Payload: Any> : SpectaclesRequest

Properties

onResponse
abstract val onResponse: Consumer<Payload>

Invoked to deliver a successful response.

onError
abstract val onError: Consumer<SpectaclesRequestException>

Invoked to report an error.

SpectaclesRequest.WithResponses

Represents a request that may produce multiple responses (e.g., a subscription).

abstract class WithResponses<Payload: Any> : SpectaclesRequest

Properties

onResponse
abstract val onResponse: Consumer<Payload>

Invoked to deliver a successful response.

onError
abstract val onError: Consumer<SpectaclesRequestException>

Invoked to report an error.

SpectaclesRequest.Response

Base class for all response types.

sealed class Response<Payload: Any>

Properties

payload
abstract val payload: Payload

The concrete response payload.

SpectaclesRequest.Response.Ongoing

Represents an intermediate response, indicating that more responses will follow. Typically used for subscription-style requests.

data class Ongoing<Payload: Any>(
override val payload: Payload
) : Response<Payload>

SpectaclesRequest.Response.Complete

Represents the final response. Once a Complete is delivered, no further responses will be sent for the request.

data class Complete<Payload: Any>(
override val payload: Payload
) : Response<Payload>

SpectaclesApiReques

Base interface for all Lens API requests.

sealed interface SpectaclesApiRequest

SpectaclesApiRequest.Payload

Encapsulates the method name and raw parameters for an API request.

data class Payload(
val method: String,
val params: ByteArray
)

Properties

method
val method: String

The name of the API method being invoked.

params
val params: ByteArray

The serialized parameters for the API method.

SpectaclesApiRequest.Call

Represents an API call that expects one or more responses (e.g., a request or subscription).

data class Call(
val payload: Payload,
override val onResponse: Consumer<Payload>
override val onError: Consumer<SpectaclesRequestException>
) : SpectaclesApiRequest, SpectaclesRequest.WithResponses<ByteArray>()

Properties

payload
val payload: Payload

The payload (method and parameters) of this API call.

onResponse
val onResponse: Consumer<Payload>

Called to deliver one or more successful responses.

onError
val onError: Consumer<SpectaclesRequestException>

Called to report an error.

SpectaclesApiRequest.Notify

Represents a one-way API notification (event) that does not expect a response.

data class Notify(
val payload: Payload
) : SpectaclesApiRequest, SpectaclesRequest.WithoutResponses()

Properties

payload
val payload: Payload

The payload (method and parameters) of this API notification.

SpectaclesAssetRequest

Base interface for all Lens asset requests.

sealed interface SpectaclesAssetRequest

SpectaclesAssetRequest.Load

Represents a request from the Lens to load a SpectaclesAsset from the app.

data class Load(
val path: String,
val version: String?,
override val onResponse: Consumer<SpectaclesAsset>,
override val onError: Consumer<SpectaclesRequestException>,
) : SpectaclesAssetRequest, SpectaclesRequest.WithResponse<SpectaclesAsset>()

Properties

path
val path: String

The path or URI of the requested SpectaclesAsset.

version
val version: String?

The version of the asset currently cached on Spectacles (if any). This may be a file checksum or timestamp, as determined by the SDK or Lens developer.
The app can use this to decide whether to:

  • return a new version of the asset, or
  • indicate that the cached version is still up-to-date.
onResponse
val onResponse: Consumer<SpectaclesAsset>

Called to deliver the asset response to the Lens. Should be invoked exactly once.

onError
val onError: Consumer<SpectaclesRequestException>

Called to report an error if the asset cannot be provided.

SpectaclesAsset

Base class for responses payload to a SpectaclesAssetRequest.

sealed class SpectaclesAsset

SpectaclesAsset.Content

Represents the content of an asset to be delivered to the Lens.

data class Content(
val version: String?,
val assetSize: Long,
val dataStream: InputStream
) : SpectaclesAsset()

Properties

version
val version: String?

The version identifier of the asset being delivered.

This will be returned back to the app in future requests for version comparison.

assetSize
val assetSize: Long

The total size of the asset in bytes.

dataStream
val dataStream: InputStream

The binary content of the asset, streamed to the Lens.

SpectaclesAsset.UpToDate

Indicates that the cached version of the asset on Spectacles is current and does not need to be updated.

data object UpToDate : SpectaclesAsset()

SpectaclesRequestException

Exception thrown when a request to the Spectacles fails.

open class SpectaclesRequestException(
statusCode: Int
) : SpectaclesStreamException(statusCode) {

/**
* Default state or unset.
*/
data object Unknown : SpectaclesRequestException(500)

/**
* Redirected. Corresponds to the 3XX HTTP response status codes.
*/
data object Redirected : SpectaclesRequestException(302)

/**
* Bad request. Corresponds to the 4XX HTTP response status codes other
* than 401, 403, 404, 408, 413, 414, and 431.
*/
data object BadRequest : SpectaclesRequestException(400)

/**
* Access denied. Corresponds to the HTTP response status codes 401 and 403.
*/
data object AccessDenied : SpectaclesRequestException(403)

/**
* Not found. Corresponds to the HTTP response status code 404.
*/
data object NotFound : SpectaclesRequestException(404)

/**
* Timeout. Corresponds to the HTTP response status codes 408 and 504.
*/
data object Timeout : SpectaclesRequestException(504)

/**
* Request too large. Corresponds to the HTTP response status codes 413, 414, and 431.
*/
data object RequestTooLarge : SpectaclesRequestException(413)

/**
* Server error. Corresponds to the 5XX HTTP response status codes other than 504.
*/
data object ServerError : SpectaclesRequestException(500)

/**
* Request cancelled by the caller.
*/
data object RequestCancelled : SpectaclesRequestException(409)

/**
* Internal error in the remote API framework.
*/
data object InternalError : SpectaclesRequestException(500)
}

Log

Interface for logging functionality.

Allows setting a custom logging provider that can be used across the application.

interface Log

Properties

provider
@JvmStatic val provider: ((String) -> Log?)? = null

Holds the current logging provider instance used to create Log instances.

If set to null, logging will be disabled.

Methods

get
@JvmStatic fun get(String): Log

Retrieves a Log instance associated with the given tag.

enabled
fun enabled(): Boolean

Returns true if logging is enabled.

verbose
fun verbose(message: () -> String)

Sends a VERBOSE log message.

info
fun info(message: () -> String)

Sends an INFO log message.

debug
fun debug(message: () -> String)

Sends a DEBUG log message.

warn
fun warn(message: () -> String)

Sends a WRAN message without a stack trace.

warn
fun warn(throwable: Throwable, message: () -> String)

Sends a WRAN message with a stack trace.

err
fun err(message: () -> String)

Sends an ERROR message without a stack trace.

err
fun err(throwable: Throwable, message: () -> String)

Sends an ERROR message with a stack trace.

Log.System

This implements the Log interface using the Android logging class.

class System(private val tag: String) : Log

Log.Disabled

A built-in Log implementation that disables all logging.

All log methods are no-ops, and enabled() always returns false.

class Disabled(private val tag: String) : Log
Was this page helpful?
Yes
No