2

我正在尝试使用 Google Nearby Connections API 连接两个 Android 设备以交换数据,但没有成功。这些设备可以找到彼此,它们都无法连接到另一个。当我尝试接受连接时,它总是onConnectionInitiated()STATUS_ENDPOINT_UNKNOWN失败。

我试过了Strategy.P2P_POINT_TO_POINT Strategy.CLUSTERStrategy.STAR但我得到了相同的结果。

任何人都可以帮助我我想念什么?

两台设备都是物理设备,运行 Android 9.0

这是代码:

    public static ConnectionLifecycleCallback connectionLifecycleCallback;
    public static EndpointDiscoveryCallback endpointDiscoveryCallback;
    public static PayloadCallback payloadCallback;
    public static String SERVICE_ID;
    public Context ctx;
    public static Strategy STRATEGY;

    public NearbyHandler(Context ctx,Strategy STRATEGY){
        this.ctx = ctx;
        this.STRATEGY = STRATEGY;
        SERVICE_ID = ctx.getPackageName();
        payloadCallback = new PayloadCallback() {
            @Override
            public void onPayloadReceived(@NonNull String s, @NonNull Payload payload) {
                Log.d("NEARBY_", "PAYLOAD RECEIVED " + s);
            }

            @Override
            public void onPayloadTransferUpdate(@NonNull String s, @NonNull PayloadTransferUpdate payloadTransferUpdate) {
                Log.d("NEARBY_", "PAYLOAD TRANSFER UPDATE " + s);
            }
        };
        connectionLifecycleCallback = new ConnectionLifecycleCallback() {
            @Override
            public void onConnectionInitiated(@NonNull String s, @NonNull ConnectionInfo connectionInfo) {
                Nearby.getConnectionsClient(ctx)
                        .acceptConnection(s, payloadCallback)
                        .addOnSuccessListener(new OnSuccessListener<Void>() {
                            @Override
                            public void onSuccess(Void aVoid) {
                                Log.d("NEARBY_", "SUCCESSFULLY CONNECTED");
                            }
                        })
                        .addOnFailureListener(new OnFailureListener() {
                            @Override
                            public void onFailure(@NonNull Exception e) {
                                e.printStackTrace();
                            }
                        });
            }

            @Override
            public void onConnectionResult(@NonNull String s, @NonNull ConnectionResolution connectionResolution) {
                switch (connectionResolution.getStatus().getStatusCode()) {
                    case ConnectionsStatusCodes.STATUS_OK:
                        Nearby.getConnectionsClient(ctx).stopAdvertising();
                        Nearby.getConnectionsClient(ctx).stopDiscovery();
                        break;
                    case ConnectionsStatusCodes.STATUS_CONNECTION_REJECTED:
                        break;
                    case ConnectionsStatusCodes.STATUS_ERROR:
                        break;
                }
            }

            @Override
            public void onDisconnected(@NonNull String s) {
                Log.d("NEARBY_", "DISCONNECTED " + s);
            }
        };
        endpointDiscoveryCallback = new EndpointDiscoveryCallback() {
            @Override
            public void onEndpointFound(@NonNull String s, @NonNull DiscoveredEndpointInfo discoveredEndpointInfo) {
                Nearby.getConnectionsClient(ctx)
                        .requestConnection(
                                s,
                                ctx.getPackageName(),
                                connectionLifecycleCallback)
                        .addOnSuccessListener(new OnSuccessListener<Void>() {
                            @Override
                            public void onSuccess(Void aVoid) {
                                Log.d("NEARBY_", "ENDPOINT CONNECTED");
                            }
                        })
                        .addOnFailureListener(new OnFailureListener() {
                            @Override
                            public void onFailure(@NonNull Exception e) {
                                Log.d("NEARBY_", "FAILED TO CONNECT ENDPOINT " + e.getMessage());
                                e.printStackTrace();
                            }
                        });
            }

            @Override
            public void onEndpointLost(@NonNull String s) {
                Log.d("NEARBY_", "ENDPOINT LOST: " + s);
            }
        };
    }

    public void startDiscovering() {
        Nearby.getConnectionsClient(ctx)
                .startDiscovery(
                        SERVICE_ID,
                        endpointDiscoveryCallback,
                        new DiscoveryOptions.Builder()
                                .setStrategy(CONSTANTS.PEERTOPEER_STRATEGY).build())
                .addOnSuccessListener(new OnSuccessListener<Void>() {
                    @Override
                    public void onSuccess(Void aVoid) {
                        Log.d("NEARBY_DISCOVERER_", "onSuccess");
                    }
                })
                .addOnFailureListener(new OnFailureListener() {
                    @Override
                    public void onFailure(@NonNull Exception e) {
                        e.printStackTrace();
                    }
                });
    }

    public void startAdvertising() {
        Nearby.getConnectionsClient(ctx)
                .startAdvertising(
                        Build.MODEL,
                        SERVICE_ID,
                        connectionLifecycleCallback,
                        new AdvertisingOptions.Builder()
                                .setStrategy(CONSTANTS.PEERTOPEER_STRATEGY).build())
                .addOnSuccessListener(new OnSuccessListener<Void>() {
                    @Override
                    public void onSuccess(Void aVoid) {
                    }
                })
                .addOnFailureListener(new OnFailureListener() {
                    @Override
                    public void onFailure(@NonNull Exception e) {
                        e.printStackTrace();
                    }
                });
    }
}
NearbyHandler nearby = new NearbyHandler(getApplicationContext(), Strategy.P2P_POINT_TO_POINT);
if (IS_DEVICE_A) {
      nearby.startAdvertising();
} else {
      nearby.startDiscovering();
}

更新:谷歌的对讲机演示应用在两部手机上都能正常运行。

4

1 回答 1

0

最后我设法让它工作,但不确定这个问题。我管理连接生命周期的方式与 API Docs 中的方式有​​点不同。

所以我创建了一个私人助手类

class Endpoint {
    @NonNull
    private final String id;
    @NonNull
    private final String name;

    public Endpoint(@NonNull String id, @NonNull String name) {
        this.id = id;
        this.name = name;
    }

    @NonNull
    public String getId() {
        return id;
    }

    @NonNull
    public String getName() {
        return name;
    }

    @Override
    public boolean equals(Object obj) {
        if (obj instanceof Endpoint) {
            Endpoint other = (Endpoint) obj;
            return id.equals(other.id);
        }
        return false;
    }

    @Override
    public int hashCode() {
        return id.hashCode();
    }

    @Override
    public String toString() {
        return String.format("Endpoint{id=%s, name=%s}", id, name);
    }
}

和应该如下所示ConnectionLifecycleCallback()EndpointDiscoveryCallback()

endpointDiscoveryCallback = new EndpointDiscoveryCallback() {
    @Override
    public void onEndpointFound(@NonNull String s, @NonNull DiscoveredEndpointInfo discoveredEndpointInfo) {
        Endpoint endpoint = new Endpoint(s, discoveredEndpointInfo.getEndpointName());
        ConnectionsClient c = Nearby.getConnectionsClient(ctx);
        c.requestConnection(endpoint.getName(), endpoint.getId(), connectionLifecycleCallback).addOnSuccessListener(new OnSuccessListener < Void > () {
            @Override
            public void onSuccess(Void aVoid) {}
        });
    }

    @Override
    public void onEndpointLost(@NonNull String s) {}
};



connectionLifecycleCallback = new ConnectionLifecycleCallback() {
    @Override
    public void onConnectionInitiated(@NonNull String s, @NonNull ConnectionInfo connectionInfo) {
        Nearby.getConnectionsClient(ctx).stopAdvertising();
        Nearby.getConnectionsClient(ctx).stopDiscovery();
        Endpoint endpoint = new Endpoint(s, connectionInfo.getEndpointName());
        ConnectionsClient c = Nearby.getConnectionsClient(ctx);
        c.acceptConnection(endpoint.getId(), payloadCallback).addOnSuccessListener(new OnSuccessListener < Void > () {
            @Override
            public void onSuccess(Void aVoid) {}
        });
    }

    @Override
    public void onConnectionResult(@NonNull String s, @NonNull ConnectionResolution connectionResolution) {
        switch (connectionResolution.getStatus().getStatusCode()) {
            case ConnectionsStatusCodes.STATUS_OK:
                Nearby.getConnectionsClient(ctx).stopAdvertising();
                Nearby.getConnectionsClient(ctx).stopDiscovery();
                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;
        }
    }
    @Override
    public void onDisconnected(@NonNull String s) {}
};
于 2020-12-20T09:52:39.780 回答