- Как программно подключиться к другой сети Wi-Fi в Android API уровня 29 и выше (> = 29)
- 2 ответа
- Android 10 / API 29 : how to connect the phone to a configured network?
- 3 Answers 3
- How do I connect to a specific Wi-Fi network in Android programmatically?
- 11 Answers 11
- Connect to Wifi in Android Q programmatically
- 7 Answers 7
- Android API to Connect to Wifi Network
- 2 Answers 2
Как программно подключиться к другой сети Wi-Fi в Android API уровня 29 и выше (> = 29)
Usecase : успешно подключитесь к другим указанным сетям Wi-Fi и отключитесь от существующей сети Wi-Fi.
Я попытался WifiNetworkSpecifier и WifiNetworkSuggestion подключиться к другому Wi-Fi программно в Android. Когда я попытался использовать WifiNetworkSpecifier, я вижу диалоговое окно с просьбой подключиться к указанной сети. Но после нажатия кнопки «Подключиться» я не могу получить доступ к Интернету и отключаюсь от сети Wi-Fi при закрытии / закрытии приложения. Принимая во внимание, что WifiNetworkSuggestion не работает для меня с приведенным ниже кодом (разрешение на местоположение гарантировано).
Код, используемый для WifiNetworkSpecifier :
Код, используемый для WifiNetworkSuggestion (я думаю, что для моего сценария использования мне нужно использовать его согласно документации Android):
Использованные разрешения .
Любые предложения или помощь очень ценится. Спасибо!
2 ответа
В моем случае приведенный выше код работает, но я отключил сеть от Wi-Fi Picker, поэтому он заблокировал меня на 24 часа. По этой причине я не работал в то время. Несколько ограничений, которые я заметил.
- Разрешение на расположение обязательно
- Пользователь, отклонивший уведомление о сетевом предложении, удаляет разрешение CHANGE_WIFI_STATE из приложения, т.е. Когда пользователь нажимает «Нет» в уведомлении. Они не могут подключиться к Wi-Fi. Пользователь может предоставить это утверждение позже, зайдя в меню управления Wi-Fi (Настройки> Приложения и уведомления> Доступ к специальному приложению> Управление Wi-Fi> Имя приложения) — Документация Android.
- После успешного подключения к Wi-Fi удаление приложения приведет к отключению в сети Wi-Fi
Вам необходимо зарегистрироваться NetworkCallbck() onResume:
Что касается wifiManager.addNetworkSuggestions , добавьте это:
Если все пройдет хорошо, появится уведомление, позволяющее вашему приложению подключиться к сети. Нажмите «Да» и подождите, пока возврат к сети. Это может занять некоторое время. В моем случае я должен ждать 1 минуту, чтобы Wi-Fi был подключен. Также нет необходимости регистрировать вещательный приемник. Наконец, отмените регистрацию в сети.
Источник
Android 10 / API 29 : how to connect the phone to a configured network?
I am working on an application in which one the user has to follow these steps :
- connect the phone to wifi ;
- connect the phone to a dedicated hotspot from a connected object.
When the user is connected to the dedicated hotspot of the connected object, the application does some HTTP requests in order to configure it. Then, I would like to reconnect automatically the application to the global wifi of step 1.
From API 21 to API 28 this feature is very easy to implement because I know the SSID I want to reconnect the phone too. It can be done with a few line of code:
On API 29 this simple code does not work anymore according to this article: https://developer.android.com/about/versions/10/privacy/changes#configure-wifi
According to the article, now, I should use 2 classes: WifiNetworkSpecifier and/or WifiNetworkSuggestion .
Unfortunately, I cannot find a working example using these classes in order to connect the user to a previous configured SSID.
Does someone already achieve that?
Thank you in advance for your help.
3 Answers 3
Just in case any poor soul encounters this, it’s completely possible the API is just broken on your device. On my OnePlus 5, Android 10, Build 200513, this happens:
- Call requestNetwork. Doesn’t matter whether I use the Listener or PendingIntent version
- The OS finds the network, connects, onAvailable and friends are called
- OS immediately disconnects. I can see «App released request, cancelling NetworkRequest» in logcat
- This is however, not true — the request was not cancelled, which Android relizes, and starts the process of connecting to the network again. Go to 2. and repeats forever.
Additionally, you can get the OS into state when it will no longer show the «Device to use with » dialog if you don’t terminate your app and the dialogs in the correct order, and only reboot helps.
Just save yourself the trouble, target Android 9 and use the WifiManager APIs (that are helpfully broken if you target 10). It even has better user experience than the new requestNetwork APIs.
Источник
How do I connect to a specific Wi-Fi network in Android programmatically?
I want to design an app which shows a list of Wi-Fi networks available and connect to whichever network is selected by the user.
I have implemented the part showing the scan results. Now I want to connect to a particular network selected by the user from the list of scan results.
How do I do this?
11 Answers 11
You need to create WifiConfiguration instance like this:
Then, for WEP network you need to do this:
For WPA network you need to add passphrase like this:
For Open network you need to do this:
Then, you need to add it to Android wifi manager settings:
And finally, you might need to enable it, so Android connects to it:
UPD: In case of WEP, if your password is in hex, you do not need to surround it with quotes.
The earlier answer works, but the solution can actually be simpler. Looping through the configured networks list is not required as you get the network id when you add the network through the WifiManager.
So the complete, simplified solution would look something like this:
Before connecting WIFI network you need to check security type of the WIFI network ScanResult class has a capabilities. This field gives you type of network
There are three types of WIFI networks.
First, instantiate a WifiConfiguration object and fill in the network’s SSID (note that it has to be enclosed in double quotes), set the initial state to disabled, and specify the network’s priority (numbers around 40 seem to work well).
Now for the more complicated part: we need to fill several members of WifiConfiguration to specify the network’s security mode. For open networks.
For networks using WEP; note that the WEP key is also enclosed in double quotes.
For networks using WPA and WPA2, we can set the same values for either.
Finally, we can add the network to the WifiManager’s known list
Источник
Connect to Wifi in Android Q programmatically
I had this function to connect in Wifi network, below Android 10 it works fine, but when I tried on Android 10, I had a successful connection but WITHOUT internet, I knew it’s a bug in Android 10 but I found this application which can connect to wifi from Android 10 with no problem. I’m blocked for days.
7 Answers 7
So far what is working for me on the majority of devices I have tested with, with a fallback option to at least stop the dreaded ‘looping request’ and to allow a successful manual connection
The below code is written in Kotlin, please google how to covert to Java if needed.
Create a NetworkCallback which is required for API >= 29 (prior it was not required but could be used)
Connect to a network as follows:
As stated here by Google, some OEM Roms are not ‘holding on to the request’ and therefore the connection is dropping instantly. OnePlus have fixed this problem in some of their later models but not all. This bug will continuously exist for certain phone models on certain Android builds, therefore a successful fallback (i.e. a manual connection with no network disruption) is required. No known workaround is available, but if found I will update it here as an option.
To remove the network, do the following:
Please keep in mind, an automatic connection allows for an automatic & manual disconnection. A manual connection (such as the suggested fallback for OnePlus devices) does not allow an automatic disconnection. This will also need to be handled within the app for a better UX design when it comes to IoT devices.
Some extra small tips & info:
now that a system dialog opens, the app calls onPause and onResume respectively. This affected my logic regarding automatic connection to IoT devices. In some case, onResume is called before the network callback is finished.
In regards to tests, I have yet to be able to get around the dialog by just using espresso and it may block some tests that were working before API 29. It may be possible using other frameworks such as uiautomator. In my case I adjusted the tests to work up until the dialog shows, and run further tests thereafter. Using Intents.init() does not work.
onUnavailable is called when the the network has been found, but the user cancels. It is not called when the network was not found or if the user cancels the dialog before the network has been found, in this case no other methods are called, use onResume to catch it.
when it fails on the OnePlus it called onAvailable() -> onCapabilitiesChanged() -> onBlockedStatusChanged (blocked: false) -> onCapabilitiesChanged() -> onLost() respectively
removeCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET) wont help keep the connection on a OnePlus as stated here
setting the Bssid wont help keep the connection on a OnePlus as stated here
google cannot help, they have stated it is out of their hands here
OnePlus forum posts confirming it working for some models (but not all) after an update, see here, here & here
when GPS is switched off, the SSID names of networks are not available
if the dialog comes several times, check your own activity lifecycle, in my case some models were calling onResume before the network callback was received.
manually connecting to a network without internet capabilities needs user confirmation to keep the connection (sometimes in the form of a dialog or as a notification), if ignored, the system will disconnect from the network shortly afterwards
List of devices tested:
- Google Pixel 2 — No issues found
- Samsung S10 SM-G970F — No issues found
- Samsung S9 SM-G960F — No issues found
- One Plus A5000 (OxegenOS 10.0.1) — Major Issue with automatic connection
- HTC One M8 (LineageOS 17.1) — No issues found
- Xiaomi Mi Note 10 — Issue with disconnecting (Fixed, see code example)
- Samsung A50 — Dialog repetitively appears after successful connection (sometimes)
- Huawei Mate Pro 20 — Dialog repetitively appears after successful connection (sometimes)
- Huawei P40 Lite — Doesn’t call onLost()
- CAT S62 Pro — No issues found
- Sony Xperia SZ2 — No issues found
- Samsung Note10 — No issues found
Источник
Android API to Connect to Wifi Network
I’m totaly lost in the versions of WiFi APIs. I want to connect to a configured WiFi Network programmaticaly. As decribed in this question: Connect to wifi network Android programmatically
I develop on Android 10 and want to write a code that is also compatible with older Android Versions.
On my android 10 the code described does not work. What code do I need to implement the functionality on Android 10?
What do I do to write an application that also runs on my other Android 9 phone?
2 Answers 2
From Android Q, connecting to Wifi Network has changes a lot.
First of all the code you are using or @matdev mentioned uses API public int addNetwork (WifiConfiguration config) from WifiManager is deprecated in Android 10 and will return -1 as networkID.
From Android Q, two classes are suggested for Wifi connection. But each of them has its own advantage and disadvantage.
A code example from WifiUtil Library
My observation with this implementation is — It is more like P2P communication, and at this time other application from the same device cannot use internet from the connected WiFi network
A code example from developer.android.com
My observation with the above mentioned implementation is, when you call the wifiManager.addNetworkSuggestions it return success and show user a notification for connection. If the user accept, device gets connected to the WiFi network and other app can user internet. But if user disconnect from network and you call wifiManager.addNetworkSuggestions again, it will return WifiManager.STATUS_NETWORK_SUGGESTIONS_ERROR_ADD_DUPLICATE error.
It looks like this API just provide a suggestion list of networks where the device can auto connect. But the connection will be determined by the OS.
But if you really need a solution, an undocumented way use to the Default Wifi QR Code Scanner from Android Source that can detect both QR Code schems Zxing and DPP.
Источник