Matrix Android SDK2

repository·develop·Indexed 41 days ago

https://github.com/matrix-org/matrix-android-sdk2

A Matrix SDK for Android extracted from the Element Android application, designed to replace the legacy Matrix Android SDK. It provides core Matrix functionality via a hierarchical service model, including the Matrix root object, AuthenticationService, Session management, and RoomService. Version 1.2.1.

Tokens
4.5K
Snippets
14
Records
23
Agent score
45%

What's inside Matrix Android SDK2

  1. Understand the Matrix SDK entry points and service hierarchy

    develop

    The Matrix Android SDK is structured around a hierarchical service model. To interact with the Matrix network, you follow this flow:

    1. Initialize the SDK: Create and manage a Matrix object. This is the primary entry point.
    2. Authentication: Use the Matrix object to access the AuthenticationService. This service allows you to:
      • Retrieve an existing Session.
      • Create a new Session using a LoginWizard or a RegistrationWizard.
    3. Session Management: Once you have a Session object, you can access various domain-specific services, such as the RoomService.
    4. Room Interaction: Use the RoomService to list rooms, create new rooms, or retrieve a specific Room object.
    5. Room Features: From a Room object, you can perform actions like retrieving a Timeline or sending messages.
  2. Integrate matrix-android-sdk2 into your application

    develop

    To use the Matrix Android SDK2 in your Android project, add the following Gradle dependency to your application module's build.gradle file. This SDK is an extract from Element Android and provides the core Matrix functionality for Android applications.

    implementation 'org.matrix.android:matrix-android-sdk2:1.2.1'
  3. Explore SDK usage examples in org.matrix.android.sdk.userstories

    develop
    The org.matrix.android.sdk.userstories package contains practical implementation examples of common user workflows. These classes use the Us prefix (e.g., UsLogin, UsSendMessage) and serve as a guide for understanding how to combine various SDK APIs to accomplish specific tasks like authentication, messaging, or room management.
  4. How SecretStoringUtils works for secure storage

    develop

    SecretStoringUtils provides a high-level API to securely store sensitive data (bytes or objects) on Android using the Android Keystore. It abstracts away the complexity of managing encryption keys and handles different Android OS versions automatically:

    • Android M (API 23) and above: Uses the Keystore to generate and manage symmetric AES keys directly. This is more efficient and secure.
    • Android < M (Lollipop and below): Uses the Keystore to manage an RSA key pair. For every secret, a random AES key is generated, encrypted with the RSA public key, and stored alongside the encrypted secret.

    Important Security Note: Keys stored in the Keystore can be wiped by the OS (e.g., if the user changes their device lock screen/PIN or biometric settings). If keys are lost, previously encrypted data will become unrecoverable.

    val secret = "The answer is 42"
    val KEncrypted = SecretStoringUtils.securelyStoreString(secret, "myAlias")
    // ... store KEncrypted anywhere (e.g. SharedPreferences)
    
    // To retrieve:
    val kDecrypted = SecretStoringUtils.loadSecureSecret(KEncrypted, "myAlias")
  5. Migrating from the legacy Matrix Android SDK

    develop

    There is no official migration path or documentation for moving from the legacy Matrix Android SDK to matrix-android-sdk2. Because the API surface is entirely new, a direct migration is not expected to be straightforward.

    Recommendation: Use matrix-android-sdk2 for all new applications.

  6. Identify core SDK service classes

    develop

    The following classes represent the primary API surface for interacting with the Matrix network:

    • org.matrix.android.sdk.api.Matrix: The root object for the SDK.
    • org.matrix.android.sdk.api.auth.AuthenticationService: Handles login and registration flows.
    • org.matrix.android.sdk.api.auth.login.LoginWizard: Facilitates existing user login.
    • org.matrix.android.sdk.api.auth.registration.RegistrationWizard: Facilitates new user registration.
    • org.matrix.android.sdk.api.session.Session: Represents an authenticated user session.
    • org.matrix.android.sdk.api.session.room.RoomService: Provides access to room-related operations.
    • org.matrix.android.sdk.api.session.room.Room: Represents an individual chat room.
    • org.matrix.android.sdk.api.session.room.timeline.Timeline: Represents the message history within a room.
  7. Get SDK and Crypto versions

    develop

    The Matrix companion object provides methods to retrieve version information for troubleshooting and logging.

    • getSdkVersion(): Returns a string containing the SDK version and the Git revision.
    • getCryptoVersion(longFormat: Boolean): Returns the version of the underlying Rust crypto components. If longFormat is true, it includes the Git hash and the Vodozemac version.
    val sdkVersion = Matrix.getSdkVersion()
    val cryptoVersion = Matrix.getCryptoVersion(longFormat = true)
  8. Use HomeServerConnectionConfig.Builder to create configurations

    develop

    The HomeServerConnectionConfig.Builder provides a fluent API to set up connection parameters.

    URI Methods

    • withHomeServerUri(hsUriString: String) or withHomeServerUri(hsUri: Uri): Sets the main homeserver URI. Must use http or https schemes.
    • withIdentityServerUri(identityServerUriString: String) or withIdentityServerUri(identityServerUri: Uri): Sets the identity server URI.
    • withAntiVirusServerUri(antivirusServerUriString: String?) or withAntiVirusServerUri(antivirusServerUri: Uri?): Sets the anti-virus server URI.

    Security & TLS Methods

    • withAllowedFingerPrints(allowedFingerprints: List<Fingerprint>?): Adds a list of allowed SSL fingerprints.
    • withPin(pin: Boolean): Enables or disables certificate pinning.
    • addAcceptedTlsVersion(tlsVersion: TlsVersion): Adds a specific TLS version to the accepted list.
    • addAcceptedTlsCipherSuite(tlsCipherSuite: CipherSuite): Adds a specific TLS cipher suite to the accepted list.
    • forceUsageOfTlsVersions(forceUsageOfTlsVersions: Boolean): Forces the use of specified TLS versions. This is useful for older devices (Android < 20).
    • withShouldAcceptTlsExtensions(shouldAcceptTlsExtension: Boolean): Configures whether to accept TLS extensions.

    Other Methods

    • withAllowHttpConnection(allowHttpExtension: Boolean): Enables/disables HTTP (non-HTTPS) connections.
    • build(): Finalizes the configuration and returns the HomeServerConnectionConfig instance.
    val builder = HomeServerConnectionConfig.Builder()
        .withHomeServerUri("https://example.com/")
        .addAcceptedTlsVersion(TlsVersion.TLS_1_3)
        .addAcceptedTlsCipherSuite(CipherSuite.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256)
        .withAllowHttpConnection(false)
    
    val config = builder.build()
  9. Use MatrixCallback for asynchronous operations

    develop

    The MatrixCallback<T> interface is used to handle the results of asynchronous SDK operations. It provides two primary hooks: onSuccess(data: T) which is called when an operation completes successfully with the requested data, and onFailure(failure: Throwable) which is called when an error occurs. Both methods have default no-op implementations, allowing you to implement only the one you need.

    class MyCallback : MatrixCallback<String> {
        override fun onSuccess(data: String) {
            // Handle successful data
        }
    
        override fun onFailure(failure: Throwable) {
            // Handle error
        }
    }