Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
112 views
in Technique[技术] by (71.8m points)

java - Creating a custom wifi setup

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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)

A notification which is generated by the android Wi-Fi suggestion API

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...