ACTION_PICK_WIFI_NETWORK on a dialog with avaliable networks

前端 未结 2 1336
故里飘歌
故里飘歌 2021-01-14 15:41

I\'m trying to create a Dialog which shows something like ACTION_PICK_WIFI_NETWORK but instead of open Android Settings / WiFi open it

2条回答
  •  我在风中等你
    2021-01-14 16:26

    I found the library WifiUtils to be extremely useful. To connect to a selected wifi network, create connectToWifi(ssid, pass)

    private fun connectToWifi(ssid: String, password: String) {
        WifiUtils.withContext(applicationContext)
          .connectWith(ssid, password)
          .onConnectionResult(::connectWifiResultListener)
          .start()
    }
    

    Then, replace Toast.makeText(getApplicationContext(), "Selected " + strName, Toast.LENGTH_SHORT).show(); in showWifiListDialog setAdapter onClick with connectToWifi(strName, password)

    The password can be empty "" if the wifi network doesn't require authentication

    The result will return to connectWifiResultListener

     private fun connectWifiResultListener(isSuccess: Boolean) {
        if (isSuccess)
          // do something
        else}
          // show error
    }
    

    In addition, I adapted scanWifi from the WifiUtils library with @Skizo-ozᴉʞS wifi scanning solution and it worked like a charm. So, instead of the startWifiScans method and the wifiReceiver which calls showWifiListDialog(results) I used

    WifiUtils.withContext(applicationContext).scanWifi(::getScanResults).start()
    

    And call showWifiListDialog in getScanResults

    private fun getScanResults(results: List) {
        if (results.isEmpty()) { return }
        showWifiListDialog(results)
      }
    

提交回复
热议问题