2017-09-14 64 views
1

我正在開發基於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 

我假裝與超時是爲了避免等待,直到青睞的設備找到另一個與之配對的連接。有沒有人有這個問題?

回答

0

同時,我已經實現瞭解決方法是增加一個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更好的實現,但它仍然有效。