启动发现和开始广告超时不适用于Android附近
问题描述:
我正在开发基于Android Nearby的项目。我能为操作添加超时的请求连接或发送有效载荷,但它已经不可能,使其工作在发现和广告流程...启动发现和开始广告超时不适用于Android附近
Nearby.Connections.startDiscovery(
googleApiClient,
getServiceId(),
object : EndpointDiscoveryCallback() {
override fun onEndpointFound(endpointId: String, info: DiscoveredEndpointInfo) {
Log.d(TAG,
String.format(
"onEndpointFound(endpointId=%s, serviceId=%s, endpointName=%s)",
endpointId, info.serviceId, info.endpointName))
if (getServiceId() == info.serviceId) {
val endpoint = Endpoint(endpointId, info.endpointName)
discoveredEndpoints.put(endpointId, endpoint)
onEndpointDiscovered(endpoint)
}
}
override fun onEndpointLost(endpointId: String) {
Log.d(TAG, String.format("onEndpointLost(endpointId=%s)", endpointId))
}
},
DiscoveryOptions(STRATEGY))
.setResultCallback({ status -> onResult(ConnectionCase.START_DISCOVERY, status) }, TIMEOUT_DISCOVERY_MILLIS, TimeUnit.MILLISECONDS)
private val TIMEOUT_DISCOVERY_MILLIS: Long = 1000
我假装与超时是为了避免等待,直到青睐的设备找到另一个与之配对的连接。有没有人有这个问题?
答
同时,我已经实现了解决方法是增加一个CountDownTimer,与所需的时间为广告超时:
private val TIMEOUT_DISCOVERY_MILLIS: Long = 15000
private val SECOND_MILLIS: Long = 1000
private fun startConnectionTimer() {
countDownTimer = object : CountDownTimer(TIMEOUT_DISCOVERY_MILLIS, SECOND_MILLIS) {
override fun onTick(millisUntilFinished: Long) {
Log.d("ADVERT", "seconds remaining: " + millisUntilFinished/SECOND_MILLIS)
}
override fun onFinish() {
if (!connectionAccepted) {
onTimeOut()
}
}
}.start()
}
//when advertising starts, this function is called:
protected fun onAdvertisingStarted() {
connectionAccepted = false
startConnectionTimer()
}
//It resets everything and stops the NearbyActions
fun onTimeOut() {
resetState()
stopNearbyActions()
onTimeOutReached()
setState(State.UNKNOWN)
}
这样一来,每个部分用户将失去连接的时间,他将在15后达到超时秒。希望它对你有帮助!等待API更好的实现,但它仍然有效。