问题描述
我想在我的应用中使用附近的连接。 现在我只使用预连接状态。我唯一应该知道的是一个设备是否在另一个设备的视线范围内。但是要求发生了变化,所以现在我需要在开始其他进程之前连接两个设备。 所以现在我有几个问题:
- 我想传递给发现者的唯一东西是一个字符串。我不需要真正的流或其他东西。但是如果我只通过一次字符串,我会在不到一分钟的时间内断开连接。但正如我之前提到的,我需要有一个开放的连接。所以现在我决定每 40 秒传递一次相同的字符串。这似乎没用,但我无法找到另一种方法来保持连接打开。
- Google 文档说:
根据您的用例,您可能希望改为显示一个列表 发现设备给用户,允许他们选择哪些设备 连接到。
private val connectionLifecycleCallback: ConnectionLifecycleCallback =
object : ConnectionLifecycleCallback() {
override fun onConnectionInitiated(endpointId: String,connectionInfo: ConnectionInfo) {
Timber.e("onConnectionInitiated $endpointId")
Nearby.getConnectionsClient(context).acceptConnection(endpointId,receiveBytesPayloadListener)
//automatic connection from both sides
}
override fun onConnectionResult(endpointId: String,result: ConnectionResolution) {
Timber.e("onConnectionResult $endpointId")
when (result.status.statusCode) {
ConnectionsstatusCodes.STATUS_OK -> {
Timber.e("onConnectionResult.STATUS_OK $endpointId ")
val bytesPayload = Payload.fromBytes("${UserRepo.rideId} ".toByteArray())
myTimer = Timer()
myTimer?.schedule(object : TimerTask() {
override fun run() {
Nearby.getConnectionsClient(context).sendPayload(endpointId,bytesPayload)
}
},40_000)
}
ConnectionsstatusCodes.STATUS_CONNECTION_REJECTED -> {
Timber.e("onConnectionResult.STATUS_CONNECTION_REJECTED ")
}
ConnectionsstatusCodes.STATUS_ERROR -> {
Timber.e("onConnectionResult.STATUS_ERROR ")
}
else -> {
}
}
}
override fun ondisconnected(endpointId: String) {
Timber.e("ondisconnected... $endpointId")
}
}
提前致谢。
解决方法
当您开始发现时,您应该传递 EndpointDiscoveryCallback,如下所示:
public void startDiscovering(EndpointDiscoveryCallback endpointDiscoveryCallback,Strategy strategy){
DiscoveryOptions discoveryOptions = new DiscoveryOptions.Builder().setStrategy(strategy).build();
connectionsClient.startDiscovery(
SERVICE_ID,endpointDiscoveryCallback,discoveryOptions)
.addOnSuccessListener(
(Void unused) -> {
Log.e("Discovery Start","Discovery started successfully");
}).addOnFailureListener(
(Exception e) -> {
Log.e("Discovery Start",e.getLocalizedMessage());
});
}
每次在您附近发现新设备时,此 EndpointDiscoveryCallback 都会为您提供端点信息。这将允许您列出已发现的设备。
public class MyEndpointDiscoveryCallback extends EndpointDiscoveryCallback {
@Override
public void onEndpointFound(@NonNull String endpointId,@NonNull DiscoveredEndpointInfo discoveredEndpointInfo) {
// new device discovered
}
@Override
public void onEndpointLost(@NonNull String endpointId) {
// discovered device lost
}
}