Commissioning API on Android

The Commissioning API allows an app to commission to either:

  • Your fabric and the Google fabric.
  • Only the Google fabric.

Ways to commission Matter devices

The commissioning process can be initiated:

Request commissioning directly in your app

Requesting commissioning directly in the app can be triggered by a button in the app, and can be done in two ways:

For single fabrics

To request commissioning:

  1. Initialize an ActivityResultLauncher in your activity and call CommissioningResult.fromIntentSenderResult to parse the activity result. If the user commissioned the device on the Google fabric, the result may include the name the user assigned to the device during setup. If commissioning fails or is canceled, fromIntentSenderResult throws a MatterCommissioningApiException (a subclass of ApiException). For details on commissioning error codes, see Handle commissioning errors.

    private val commissioningLauncher =
      registerForActivityResult(StartIntentSenderForResult()) { result ->
        try {
          val commissioningResult =
            CommissioningResult.fromIntentSenderResult(
              result.resultCode,
              result.data,
            )
          Log.i(
            "CommissioningActivity",
            "Commissioning success: ${commissioningResult.deviceName}",
          )
        } catch (e: MatterCommissioningApiException) {
          val details = e.errorDetails
          Log.e(
            "CommissioningActivity",
            "Commissioning failed with status ${e.statusCode}: " +
              "googleErrorCode=${details.googleErrorCode}, " +
              "matterErrorType=${details.matterErrorType}, " +
              "matterErrorValue=${details.matterErrorValue}",
            e,
          )
        } catch (e: ApiException) {
          Log.e(
            "CommissioningActivity",
            "Commissioning failed with status ${e.statusCode}",
            e,
          )
        }
      }
    
  2. Construct a CommissioningRequest, including the received payload data, and set the option to commission the device to the Google fabric, using setStoreToGoogleFabric:

    val commissioningRequest = CommissioningRequest.builder()
            .setOnboardingPayload(payload)
            .setStoreToGoogleFabric(true)
      // set all other options that you care about
            .build()
    

    If you want to commission the device to the Google fabric as well as your own fabric, set your commissioning service with setCommissioningService in the CommissioningRequest.

  3. Use the CommissioningClient instance to start commissioning:

    commissioningClient
      .commissionDevice(commissioningRequest)
      .addOnSuccessListener { result ->
        Log.i("CommissioningActivity", "Commissioning success")
    _commissioningIntentSender.postValue(result)
          }
          .addOnFailureListener { error ->
            Log.i("CommissioningActivity", "Commissioning failed")
      }
    

    Where _commissioningIntentSender is defined as:

    private val _commissioningIntentSender = MutableLiveData<IntentSender?>()
        val commissioningIntentSender: LiveData<IntentSender?>
        get() = _commissioningIntentSender
    
  4. Once the CommissioningClient returns the intent sender, launch the sender:

    commissioningIntentSender.observe(this) { sender ->
      if (sender != null) {
        commissioningLauncher.launch(IntentSenderRequest.Builder(sender).build())
      }
    }
    

For multiple fabrics (multi-admin)

If you need to set up multiple Matter fabrics on a device, refer to Multi-admin for Commissioning API on Android.

Matter commissioning entry point for Fast Pair or QR-code scanning (Android only)

Requesting commissioning by means of fast pair or QR code on Android can be done in two ways:

For single fabrics

Use the ACTION_START_COMMISSIONING intent filter to provide full commissioning capability for an app without needing the GHA. When commissioning to the Google fabric, this includes allowing the user to assign a name to the device.

Commissioning Flow Using ACTION_START_COMMISSIONING
Figure 1: Commissioning Flow Using ACTION_START_COMMISSIONING

To indicate support for Google fabric commissioning, add the following intent-filter to the chosen activity declaration within your AndroidManifest.xml file:

<intent-filter>
  <action android:name="com.google.android.gms.home.matter.ACTION_START_COMMISSIONING" />
  <category android:name="android.intent.category.DEFAULT" />
 </intent-filter>

The intent-filter is used to include your app in the list of suggested Matter apps in the Commissioning APIs app picker. If your app is not one of the suggested apps, it appears in the Choose other app option.

Once the user selects your app, your app is launched and directed to the chosen activity with an ACTION_START_COMMISSIONING intent.

For multiple fabrics (multi-admin)

You can also use the FastPair flow in multi-admin scenarios. For more information, refer to Multi-admin for Commissioning API on Android.

Handle the incoming intent

Once your activity is launched, it should check for the existing ACTION_START_COMMISSIONING intent and retrieve the payload:

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)

val payload = if (Matter.ACTION_START_COMMISSIONING.equals(intent.getAction())) {
      intent.getStringExtra(Matter.EXTRA_ONBOARDING_PAYLOAD)
    } else {
      null
    }
val commissioningRequest = CommissioningRequest.builder()
          .setOnboardingPayload(payload)
          .setStoreToGoogleFabric(true)
          // set all other options that you care about
          .build()
startCommissioning(commissioningRequest)
}

A payload value that is not null indicates that the user has already either scanned the device QR code, or entered the pairing key. A null payload value does not mean that the commissioning should be aborted.

Handle commissioning errors

When a commissioning flow started with CommissioningClient.commissionDevice fails or is canceled, calling CommissioningResult.fromIntentSenderResult (without filtering for result.resultCode == RESULT_OK) throws a MatterCommissioningApiException, which extends ApiException.

MatterCommissioningApiException provides an errorDetails property of type MatterCommissioningErrorDetails, which includes the Google commissioning status code (googleErrorCode) and, when a failure originates from the Matter protocol stack, the MatterCommissioningErrorDetails.MatterStatusType category (matterErrorType) and raw Matter specification code (matterErrorValue). If a failure occurs outside Matter protocol execution, such as when the user cancels setup or denies a runtime permission, both matterErrorType and matterErrorValue are null. If an error occurs before the user exits the setup flow, that error is preserved in googleErrorCode rather than being overwritten by a cancellation code.

The googleErrorCode property returns a MatterCommissioningStatusCodes constant in the 49200 to 49235 range, or 8 (CommonStatusCodes.INTERNAL_ERROR) when an internal commissioning stage failure is described primarily by matterErrorType and matterErrorValue. Always include an else branch when matching googleErrorCode values in a when expression.

The following example shows how to catch MatterCommissioningApiException, inspect MatterCommissioningErrorDetails, and branch on specific googleErrorCode values:

fun handleCommissioningResult(result: ActivityResult) {
  try {
    val commissioningResult =
      CommissioningResult.fromIntentSenderResult(result.resultCode, result.data)
    Log.i(
      "CommissioningActivity",
      "Commissioned device: ${commissioningResult.deviceName}",
    )
  } catch (e: MatterCommissioningApiException) {
    val details = e.errorDetails
    val matterStatusType =
      MatterCommissioningErrorDetails.MatterStatusType.entries.find {
        it.typeId == details.matterErrorType
      }
    when (details.googleErrorCode) {
      MatterCommissioningStatusCodes.PASE_PASSCODE_INVALID ->
        Log.e("CommissioningActivity", "Invalid setup passcode", e)
      MatterCommissioningStatusCodes.COMMISSIONEE_FAILED_TO_JOIN_NETWORK ->
        Log.e(
          "CommissioningActivity",
          "Device failed to join Wi-Fi " +
            "(network status=${details.matterErrorValue})",
          e,
        )
      MatterCommissioningStatusCodes.SETUP_CANCELED_BY_USER ->
        Log.i("CommissioningActivity", "User canceled setup")
      MatterCommissioningStatusCodes.INTERNAL_ERROR ->
        Log.e(
          "CommissioningActivity",
          "Internal commissioning failure (" +
            "matterStatusType=$matterStatusType, " +
            "matterErrorValue=${details.matterErrorValue})",
          e,
        )
      else -> {
        val errorString =
          MatterCommissioningStatusCodes.getStatusCodeString(
            details.googleErrorCode
          )
        Log.e(
          "CommissioningActivity",
          "Commissioning failed (status=${e.statusCode}): " +
            "googleErrorCode=$errorString (${details.googleErrorCode}), " +
            "matterStatusType=$matterStatusType, " +
            "matterErrorValue=${details.matterErrorValue}",
          e,
        )
      }
    }
  } catch (e: ApiException) {
    // Fallback for older Google Play services versions
    Log.e(
      "CommissioningActivity",
      "Commissioning failed (status=${e.statusCode})",
      e,
    )
  }
}

Suppress commissionable discovery notifications

Example of an Android halfsheet notification
Figure 1: Example of an Android halfsheet notification

By default, Google Play services on Android uses "halfsheet" notifications that cover the bottom half of a mobile device's screen to provide users with a proactive indication that commissionable Matter devices are nearby.

To prevent interruptions while your app is in the foreground, you may suppress these notifications by calling the suppressHalfSheetNotification() method. See the API documentation for more information.

The suppression enabled by this API times out if your app is in the foreground for more than 15 minutes. To re-enable suppression after a timeout, call suppressHalfSheetNotification() again, otherwise halfsheet notifications will start to appear.

How should you share Matter devices on your fabric with Google?

Google strongly recommends that you use the Commissioning API as your primary means of sharing a device that you have already set up on your own fabric with the Google fabric. The Share API has its limitations and should be reserved for other use-cases.

Why should you use the Commissioning API instead of the Share API?

The Commissioning API lets you trigger sharing a device directly with the Google fabric, which is the preferred method when viable. With the Share API, more steps are required for the end user. For example, the end user must have GHA installed, and they must know to select GHA during the process to ensure success.

To use the Commissioning API, you should open the commissioning window and call the Commissioning API, as described in How to use the Commissioning API as the secondary Matter commissioner.

When should you use the Share API?

You can use the Share API to let the end-user pick an eligible application to share a device generically with other Matter ecosystems.