Manipulating wifi network in Android
Required permissions in the manifest file.
Programmatically add a new wifi network to the WifiManager. With this new wifi network added to the WifiManager, when the device is located within this wifi network, the WifiManager will automatically connect to this new wifi network. The following code is the same as if user manually add a new wifi network in wifi settins on the phone.
fun addNewWifiNetwork() { val wifiConfig = WifiConfiguration() wifiConfig.SSID = String.format("\"%s\"", "super-fast-wifi") wifiConfig.preSharedKey = String.format("\"%s\"", "123456789") val wifiManager = applicationContext.getSystemService(Context.WIFI_SERVICE) as WifiManager wifiManager.addNetwork(wifiConfig) }
Programmatically connecting to a specific wifi network. If the device is currently connected to a wifi network, it will be disconnected. If the connection to the specified wifi network fails, it will reconnect to the previously connected wifi network. The following is the same as if the user manually selects a wifi network, enters the password and hit connect.
fun connectToANewWifiNetwork() { val wifiConfig = WifiConfiguration() wifiConfig.SSID = String.format("\"%s\"", "super-fast-wifi") wifiConfig.preSharedKey = String.format("\"%s\"", "123456789") val wifiManager = applicationContext.getSystemService(Context.WIFI_SERVICE) as WifiManager val netId = wifiManager.addNetwork(wifiConfig) wifiManager.enableNetwork(netId, true) }
Getting a list of saved wifi networks.
fun showConfiguredNetworks() { val wifiManager = applicationContext.getSystemService(Context.WIFI_SERVICE) as WifiManager for (network in wifiManager.configuredNetworks) { Log.d(TAG, "saved wifi network ssid ${network.SSID}") } }
Get currently connected wifi name.
fun getCurrentlyConnectedWifiName(): String { val manager = applicationContext.getSystemService(Context.WIFI_SERVICE) as WifiManager if (manager.isWifiEnabled) { val wifiInfo = manager.connectionInfo if (wifiInfo != null) { val state = WifiInfo.getDetailedStateOf(wifiInfo.supplicantState) if (state == DetailedState.CONNECTED || state == DetailedState.OBTAINING_IPADDR) { var ssid = wifiInfo.ssid if (ssid.startsWith("\"") && ssid.endsWith("\"")) { ssid = ssid.substring(1, ssid.length - 1) } return ssid } } } return "" }
Listen to wifi connection actions in BroadcastReceiver. The wifi BroadcastReceiver is defined as a member variable in the activity class. In the onCreate function, register this wifi BroadcastReceiver with IntentFilter with ConnectivityManager.CONNECTIVITY_ACTION so it will call the onReceive function in the wifi BroadcastReceiver whenever there is a CONNECTIVITY_ACTION action changes. In the onPause function, unregister the wifi BroadcastReceiver.
val wifiReceiver = object : BroadcastReceiver() { override fun onReceive(context: Context, intent: Intent) { if (intent.action == ConnectivityManager.CONNECTIVITY_ACTION) { val cm = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager val networkInfo = cm.activeNetworkInfo if (networkInfo == null) { Toast.makeText(context, "No Network available", Toast.LENGTH_SHORT).show() } else if (networkInfo != null && networkInfo.type == ConnectivityManager.TYPE_WIFI && networkInfo.isConnected) { val wifiManager = context.getSystemService(Context.WIFI_SERVICE) as WifiManager val wifiInfo = wifiManager.connectionInfo val ssid = wifiInfo.ssid Toast.makeText(context, "Wifi connected, " + " SSID " + ssid, Toast.LENGTH_SHORT).show() } } } } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val intentFilter = IntentFilter() intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION) registerReceiver(wifiReceiver, intentFilter) } override fun onPause() { super.onPause() unregisterReceiver(wifiReceiver) }
Print available wifi networks. This requires ACCESS_FINE_LOCATION permission from the user. Make sure the user has granted ACCESS_FINE_LOCATION permission before calling this function.
fun printAvailableWifiNetworks() { val wifiManager = applicationContext.getSystemService(Context.WIFI_SERVICE) as WifiManager wifiManager.startScan() val results = wifiManager.getScanResults() // requires ACCESS_FINE_LOCATION permission or returns nothing if (results != null) { val buf = StringBuffer() for (i in results.indices) { buf.append(results[i].SSID + "\n") } Log.d(TAG, String.format("wifi ssids:\n %s", buf.toString())) } }
References:
https://www.codexpedia.com/android/android-6-0-marshmallow-permission-handling/
https://developer.android.com/reference/android/net/wifi/WifiConfiguration.html
https://developer.android.com/reference/android/net/wifi/WifiManager.html#reconnect()
https://stackoverflow.com/questions/6517314/android-wifi-connection-programmatically
https://stackoverflow.com/questions/13563032/jelly-bean-issue-wifimanager-getconnectioninfo-getssid-extra
https://stackoverflow.com/questions/18741034/how-to-get-available-wifi-networks-and-display-them-in-a-list-in-android
https://stackoverflow.com/questions/6362314/wifi-connect-disconnect-listener
Search within Codexpedia
Search the entire web