管理連線

建立連線

找到附近的裝置後,探索者可以啟動連線。下列範例會在偵測到裝置時立即要求連線。

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.
      }
    };

視您的用途而定,您可能會想向使用者顯示可找到的裝置清單,讓使用者選擇要連線的裝置。

接受或拒絕連線

探索者要求與廣告客戶建立連線後,兩側都是透過 ConnectionLifecycleCallback 回呼的 onConnectionInitiated() 方法通知連線啟動程序。請注意,此回呼會傳入廣告客戶的 startAdvertising() 以及探索工具的 requestConnection(),但從現在開始,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();
}