จัดการการเชื่อมต่อ

เริ่มต้นการเชื่อมต่อ

เมื่อพบอุปกรณ์ที่อยู่ใกล้เคียง ผู้ค้นพบจะสามารถเริ่มการเชื่อมต่อได้ ตัวอย่างต่อไปนี้จะขอการเชื่อมต่อกับอุปกรณ์ทันทีที่ค้นพบ

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

คุณอาจต้องแสดงรายการอุปกรณ์ที่ค้นพบแก่ผู้ใช้แทน ซึ่งอุปกรณ์เหล่านี้สามารถเลือกอุปกรณ์ที่จะเชื่อมต่อได้

ยอมรับหรือปฏิเสธการเชื่อมต่อ

หลังจากผู้ค้นพบส่งคําขอเชื่อมต่อกับผู้ลงโฆษณาแล้ว ทั้ง 2 ฝ่ายจะได้รับแจ้งเกี่ยวกับกระบวนการเริ่มต้นการเชื่อมต่อผ่านเมธอด onConnectionInitiated() ของโค้ดเรียกกลับ ConnectionLifecycleCallback โปรดทราบว่าโค้ดเรียกกลับนี้จะส่งให้กับ startAdvertising() ในผู้ลงโฆษณา และ requestConnection() ในเครื่องมือค้นหา แต่นับจากนี้เป็นต้นไป API ดังกล่าวจะเป็นแบบสมมาตร

ในตอนนี้ทั้ง 2 ฝั่งต้องเลือกว่าจะยอมรับหรือปฏิเสธการเชื่อมต่อผ่านการโทรไปยัง acceptConnection() หรือ rejectConnection() ตามลําดับ การเชื่อมต่อจะเริ่มต้นขึ้นโดยสมบูรณ์เมื่อทั้ง 2 ฝั่งยอมรับ หากถูกปฏิเสธหรือทั้ง 2 กรณี ระบบจะยกเลิกการเชื่อมต่อ แต่ไม่ว่าวิธีใด ระบบจะส่งผลการค้นหาไปยัง 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.
      }
    };

ขอย้ําอีกครั้งว่า ตัวอย่างนี้จะแสดงการเชื่อมต่อที่ยอมรับโดยอัตโนมัติทั้ง 2 ฝั่ง ทั้งนี้ขึ้นอยู่กับกรณีการใช้งานของคุณ คุณอาจต้องแสดงตัวเลือกนี้ต่อผู้ใช้ในทางใดทางหนึ่ง

ตรวจสอบสิทธิ์การเชื่อมต่อ

เมื่อมีการขอการเชื่อมต่อ แอปของคุณจะตรวจสอบสิทธิ์การเชื่อมต่อได้โดยใช้โทเค็นการตรวจสอบสิทธิ์ที่มอบให้กับ onConnectionInitiated() ซึ่งเป็นวิธีให้ผู้ใช้ยืนยันว่ากําลังเชื่อมต่อกับอุปกรณ์ที่ต้องการ อุปกรณ์ทั้ง 2 เครื่องจะได้รับโทเค็นเดียวกันซึ่งเป็นสตริงสั้นๆ แบบสุ่ม คุณมีหน้าที่ตัดสินใจว่าจะยืนยันอย่างไร ซึ่งโดยปกติจะแสดงโทเค็นในอุปกรณ์ทั้งสองและขอให้ผู้ใช้เปรียบเทียบและยืนยันด้วยตนเอง เช่นเดียวกับกล่องโต้ตอบการจับคู่บลูทูธ

โค้ดตัวอย่างนี้จะแสดงวิธีการตรวจสอบสิทธิ์วิธีหนึ่งโดยแสดงโทเค็นการตรวจสอบสิทธิ์แก่ผู้ใช้ใน 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();
}