管理連線

建立連線

當找到鄰近裝置時,探索人員可以啟動連線。 以下範例會在找到裝置後立即要求連線。

private final EndpointDiscoveryCallback endpointDiscoveryCallback =
    new EndpointDiscoveryCallback() {
      @Override
      public void onEndpointFound(String endpointId, DiscoveredEndpointInfo info) {
        // An endpoint was found. We request a connection to it.
        Nearby.getConnectionsClient(context)
            .requestConnection(getLocalUserName(), endpointId, connectionLifecycleCallback)
            .addOnSuccessListener(
                (Void unused) -> {
                  // We successfully requested a connection. Now both sides
                  // must accept before the connection is established.
                })
            .addOnFailureListener(
                (Exception e) -> {
                  // Nearby Connections failed to request the connection.
                });
      }

      @Override
      public void onEndpointLost(String endpointId) {
        // A previously discovered endpoint has gone away.
      }
    };

根據您的用途,您可以改為顯示已發現的項目清單 來選擇要連接的裝置。

接受或拒絕連線

發現者要求與廣告客戶建立關係後,雙方 透過 onConnectionInitiated() 收到連線啟動程序的通知 方法 ConnectionLifecycleCallback 回呼。請注意,此回呼會傳入 startAdvertising() 探索工具的廣告客戶與 requestConnection() 但從這裡開始 API 屬於對稱式 API

現在雙方必須選擇接受或拒絕通話 分別設為 acceptConnection()rejectConnection()連結是 只有在雙方都接受時,系統才會建立完整資料庫。如果兩個或兩者皆拒絕 連線。無論您選擇哪一種,結果都會傳送到 onConnectionResult()

下列程式碼片段說明如何實作這個回呼:

private final ConnectionLifecycleCallback connectionLifecycleCallback =
    new ConnectionLifecycleCallback() {
      @Override
      public void onConnectionInitiated(String endpointId, ConnectionInfo connectionInfo) {
        // Automatically accept the connection on both sides.
        Nearby.getConnectionsClient(context).acceptConnection(endpointId, payloadCallback);
      }

      @Override
      public void onConnectionResult(String endpointId, ConnectionResolution result) {
        switch (result.getStatus().getStatusCode()) {
          case ConnectionsStatusCodes.STATUS_OK:
            // We're connected! Can now start sending and receiving data.
            break;
          case ConnectionsStatusCodes.STATUS_CONNECTION_REJECTED:
            // The connection was rejected by one or both sides.
            break;
          case ConnectionsStatusCodes.STATUS_ERROR:
            // The connection broke before it was able to be accepted.
            break;
          default:
            // Unknown status code
        }
      }

      @Override
      public void onDisconnected(String endpointId) {
        // We've been disconnected from this endpoint. No more data can be
        // sent or received.
      }
    };

再次強調,本範例顯示雙方自動接受連線,但您可以根據自己的使用情境,以某種方式向使用者顯示這個選項。

驗證連線

要求連線時,應用程式可透過以下方式「驗證」連線: 使用提供給 onConnectionInitiated() 的驗證權杖這個 能讓使用者確認,所連結的是 裝置。兩部裝置標有相同的符記,都是短隨機字串。 驗證方式完全由您決定這通常涉及顯示 並請使用者手動比較並確認 類似於藍牙配對對話方塊

此程式碼範例示範了透過顯示 AlertDialog 中使用者的驗證權杖:

@Override
public void onConnectionInitiated(String endpointId, ConnectionInfo info) {
  new AlertDialog.Builder(context)
      .setTitle("Accept connection to " + info.getEndpointName())
      .setMessage("Confirm the code matches on both devices: " + info.getAuthenticationDigits())
      .setPositiveButton(
          "Accept",
          (DialogInterface dialog, int which) ->
              // The user confirmed, so we can accept the connection.
              Nearby.getConnectionsClient(context)
                  .acceptConnection(endpointId, payloadCallback))
      .setNegativeButton(
          android.R.string.cancel,
          (DialogInterface dialog, int which) ->
              // The user canceled, so we should reject the connection.
              Nearby.getConnectionsClient(context).rejectConnection(endpointId))
      .setIcon(android.R.drawable.ic_dialog_alert)
      .show();
}