Creating a custom wifi setup

守給你的承諾、 提交于 2020-04-30 11:42:05

问题


I was just wondering if it is possible to make a custom Wifi interface within an app, where the user can input his Wifi connection instead of starting an intent which leads to the android wifi settings. I was researching this but couldn't find any useful input regarding making a custom wifi setup within the app.

startActivity( new Intent( Settings.ACTION_WIFI_SETTINGS ) );

This is not wanted... I want to crate my own wifi setup interface where the user can setup a wifi Profile and let the phone connect to a network from within an app.

Thanks for any ideas and help


回答1:


This used to be possible but is now deprecated with API level 29 (android 10). Starting with android 10, you can only add a network programmatically to a suggestion list. The user then gets a notification but isn't automatically connected. So once you set your targetsdk in you gradle file to 29 or higher, you can't automatically switch/connect to a wifi for the user.

// This only works with Android 10 and up (targetsdk = 29 and higher):
import android.net.wifi.WifiManager
import android.net.wifi.WifiNetworkSuggestion
...
val wifiManager = getSystemService(WIFI_SERVICE) as WifiManager
val networkSuggestion = WifiNetworkSuggestion.Builder()
    .setSsid("MyWifi")
    .setWpa2Passphrase("123Password")
    .build()
val list = arrayListOf(networkSuggestion)
wifiManager.addNetworkSuggestions(list)

However, you can't force a Wi-Fi switch. If the user is already connected to another Wi-Fi, he might not connect to the suggested network. See Wi-Fi suggestion API for further reference.

Up until API level 28 (android 9), this was possible with the WifiManager.

// This code works only up until API level 28 (targetsdk = 28 and lower):
import android.net.wifi.WifiConfiguration
import android.net.wifi.WifiManager
...
val wifiManager = getSystemService(WIFI_SERVICE) as WifiManager

val wifiConfiguration = WifiConfiguration()
wifiConfiguration.SSID = "\"" + "MyWifi" + "\""
wifiConfiguration.preSharedKey = "\"" + "123Password" + "\""

// Add a wifi network to the system settings
val id = wifiManager.addNetwork(wifiConfiguration)
wifiManager.saveConfiguration()

// Connect
wifiManager.enableNetwork(id, true)


来源:https://stackoverflow.com/questions/59753528/creating-a-custom-wifi-setup

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!