Wifi manager remove network suggestions

Is it possible to add a network configuration on Android Q?

I’ve noticed that in WifiManager class there is a function called addNetwork, that might be useful if I want to restore or save networks information (network name AKA SSID, together with the password and the type), so that I could also connect to it.

The problem

I can’t find much information about how to do such a thing. I’ve seen various examples on StackOverflow, and if I target Android API 28 (or below), I indeed succeed to make it add a network and even connect to it. When targeting Android 29 (Android Q), however, it fails to add the network.

What I’ve found

Since I’m trying on Pixel 2 with Android Q beta 4, I think that maybe it’s because addNetwork is deprecated, so the docs even say so, and that if I target Android Q, it won’t work, and indeed it doesn’t work:

Compatibility Note: For applications targeting Build.VERSION_CODES.Q or above, this API will always return -1.

The way it seems it should work up till Android Q (excluding), is by preparing WifiConfiguration and adding it. Later I can also connect to it if I wish. On Android Q, it seems it was replaced by WifiNetworkSuggestion, but it doesn’t seem like it’s about adding a network at all:

The Network Suggestion object is used to provide a Wi-Fi network for consideration when auto-connecting to networks. Apps cannot directly create this object, they must use WifiNetworkSuggestion.Builder#build() to obtain an instance of this object. Apps can provide a list of such networks to the platform using WifiManager#addNetworkSuggestions(List).

@WorkerThread fun addNetwork(context: Context, networkName: String, networkPassword: String? = null, keyMgmt: Int = WifiConfiguration.KeyMgmt.NONE) < val wifiManager = context.getSystemService(Context.WIFI_SERVICE) as WifiManager val conf = WifiConfiguration() conf.SSID = "\"$networkName\"" conf.preSharedKey = if (networkPassword.isNullOrEmpty()) "" else "\"$networkPassword\"" conf.allowedKeyManagement.set(keyMgmt) when (keyMgmt) < WifiConfiguration.KeyMgmt.WPA_PSK -> < //WPA/WPA2 >WifiConfiguration.KeyMgmt.IEEE8021X -> < >WifiConfiguration.KeyMgmt.WPA_EAP -> < >WifiConfiguration.KeyMgmt.NONE -> < if (networkPassword.isNullOrEmpty()) < //open network conf.wepKeys[0] = "\"\"" >else < //wep conf.wepKeys[0] = "\"" + networkPassword + "\"" conf.wepTxKeyIndex = 0 conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40) >> > if (networkPassword.isNullOrEmpty()) < //open network conf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE) >else < >wifiManager.isWifiEnabled = true while (!wifiManager.pingSupplicant()) < Log.d("AppLog", "waiting to be able to add network") >val networkId = wifiManager.addNetwork(conf) if (networkId == -1) Log.d("AppLog", "failed to add network") else < wifiManager.enableNetwork(networkId, false) Log.d("AppLog", "success to add network") >> 

But in any case, this works as long as you don’t target Android Q (API 29) and above. When you target it, I indeed always get «-1» as a result, meaning it fails. I’ve also found an issue on the issue tracker (here and I wrote about it here), telling about someone that needs the API back, but I’m not sure it’s about adding a network. Looking at WifiNetworkSuggestion , I don’t see that it has as many things to set as WifiConfiguration via its builder, so this is another reason for why I suspect it’s not about adding a network. But I tried anyway. Here’s the code I’ve tried, for example, to add a normal WPA network:

@WorkerThread fun addNetworkAndroidQ(context: Context, networkName: String, networkPassword: String? = null) < val wifiManager = context.getSystemService(Context.WIFI_SERVICE) as WifiManager val list = ArrayList() val builder = WifiNetworkSuggestion.Builder().setSsid(networkName) if (!networkPassword.isNullOrEmpty()) builder.setWpa2Passphrase(networkPassword) list.add(builder.build()) val result = wifiManager.addNetworkSuggestions(list) if (result == WifiManager.STATUS_NETWORK_SUGGESTIONS_SUCCESS) Log.d("AppLog", "success") else Log.d("AppLog", "failed") > 

enter image description here

When running (I gave it my Wifi network details, after making the OS forget about it), it says it succeeded, but nothing occurred on the OS’s Wifi settings. The network doesn’t exist there with the password I’ve added. So I really don’t get what it did. After a few long seconds, I’ve noticed a notification asking me if it’s ok to connect to the suggested networks made by the app: But still when I chose that I accept, it didn’t do anything, as before. I tried to make another POC, thinking I might have done it incorrectly, but then it didn’t even show the notification. Since I think this whole behavior is a bug, I’ve reported about it here. Not only that, but I’ve found out that if indeed it is supposed to add a network one way or another, it still has some serious restrictions, such as max added networks (here) and being removed upon uninstall of the app (here)

Читайте также:  Wifi you вай фай хакер

The questions

  1. How should Android Q be handled exactly? Is there really no API anymore to add a network?
  2. If WifiNetworkSuggestion is not about adding a network, what is it really used for exactly?
  3. Since I’m not familiar enough with the tidbits of adding a network, is my code correct about all possible ways to add a network? I ask this because someone wrote here that people should enable Wifi and make sure pingSupplicant returns true. Is it true? Or would it be enough to just call addNetwork ?
  4. If it’s now impossible to add a network using the normal API, is there maybe a solution by using a rooted device instead? Maybe some adb command?

EDIT: Not sure how to do it officially, but using adb, you might be able to add Wifi-networks on Android 11 . Need to check adb shell cmd wifi help .

Источник

Android — Cant Remove Wifi Network Programatically- The method removeNetwork(int) in the type WifiManager is not applicable for the arguments (String)

I’m attempting to remove my wifi network programatically — however I cannot seem to get it to remove/forget the currently connected wifi connection. This should be a pretty simple task — so I’m not sure exactly what I’m doing wrong. I’m using the following StackOverflow post as an example: How to forget a wireless network in android programmatically?

 public class KillTimer extends Activity < @Override public void onCreate(Bundle savedInstanceState) < super.onCreate(savedInstanceState); setContentView(R.layout.killtimer); WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE); wifiManager.getConnectionInfo().getSSID() wifiManager.getConnectionInfo().getNetoworkId(); wifiManager.removeNetwork(wifiConfig.networkId); wifiManager.saveConfiguration(); >> 

2 Answers 2

removeNetwork() takes only integer parameters. The networkSSID is a string value. That’s the cause for the error. I see that you are using SSID which is a string. You have to give the network id which is integer. You can try getConnectionInfo().getSSID() and compare with your ssid, if they are same then you can try getting getConnectionInfo().getNetoworkId() which should give the connected network’s network id, which you can use to removeNetwork.

public class KillTimer extends Activity < @Override public void onCreate(Bundle savedInstanceState) < super.onCreate(savedInstanceState); setContentView(R.layout.killtimer); WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE); int networkId = wifiManager.getConnectionInfo().getNetworkId(); wifiManager.removeNetwork(networkId); wifiManager.saveConfiguration(); >> 

Latest Updates As Of 10 June 2019

Читайте также:  Мой ноутбук перестал ловить wifi

There are some changes for Wifi Manager in Android 6.0 onwards.

Any Wi-Fi configuration created by an active Device Owner can no longer be modified or deleted by the user if WIFI_DEVICE_OWNER_CONFIGS_LOCKDOWN is non-zero.

Active Device Owners have the privilege of editing or removing any Wi-Fi configurations, including those not created by them.

Источник

RemoveNetworkSuggestions does not disconnect from WiFi Android

I’m trying to disconnect from WiFi network inside the function disconnectWiFi() using removeNetworkSuggestions but the device still stays connected to the network. I tried passing a null ArrayList as well as a list that contains the NetworkSuggestion to the RemoveNetworkSuggestions function and neither of it fixed the problem.

public class SingleWifi extends AppCompatActivity < private WifiManager wifiManager; private Button disconnectButton; ListsuggestionsList = new ArrayList(); @RequiresApi(api = Build.VERSION_CODES.Q) @Override protected void onCreate(Bundle savedInstanceState) < wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE); super.onCreate(savedInstanceState); setContentView(R.layout.activity_single_wifi); String wifiSSID = getIntent().getStringExtra("wifiList"); connectToNetwork(wifiSSID); disconnectButton = findViewById(R.id.disconnectBtn); disconnectButton.setEnabled(false); disconnectButton.setOnClickListener(new View.OnClickListener() < @Override public void onClick(View view) < disconnectWifi(); startActivity(new Intent(SingleWifi.this, MainActivity.class)); >>); > @RequiresApi(api = Build.VERSION_CODES.Q) private void disconnectWifi() < if(wifiManager != null) < wifiManager.removeNetworkSuggestions(suggestionsList); Toast.makeText(this,"Disconnect successful", Toast.LENGTH_SHORT).show(); >> @RequiresApi(api = Build.VERSION_CODES.Q) private void connectToNetwork(String ssid) < final WifiNetworkSuggestion suggestion = new WifiNetworkSuggestion.Builder() .setSsid(ssid) .setWpa2Passphrase("password") .setIsAppInteractionRequired(true) .build(); int statusCode = wifiManager.removeNetworkSuggestions(suggestionsList); suggestionsList.add(suggestion); final WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE); int status = wifiManager.addNetworkSuggestions(suggestionsList); if (status == WifiManager.STATUS_NETWORK_SUGGESTIONS_SUCCESS) < Toast.makeText(this, "Connection success", Toast.LENGTH_LONG).show(); >else if(status == WifiManager.STATUS_NETWORK_SUGGESTIONS_ERROR_ADD_DUPLICATE) < Toast.makeText(this, "Already connected, update needed", Toast.LENGTH_LONG).show(); status = wifiManager.removeNetworkSuggestions(suggestionsList); status = wifiManager.addNetworkSuggestions(suggestionsList); >final IntentFilter intentFilter = new IntentFilter(WifiManager.ACTION_WIFI_NETWORK_SUGGESTION_POST_CONNECTION); final BroadcastReceiver broadcastReceiver = new BroadcastReceiver() < @Override public void onReceive(Context context, Intent intent) < if (!intent.getAction().equals(WifiManager.ACTION_WIFI_NETWORK_SUGGESTION_POST_CONNECTION)) < return; >// Post connection disconnectButton.setEnabled(true); > >; getApplicationContext().registerReceiver(broadcastReceiver, intentFilter); > > 

removeNetworkSuggestions returns 0 so it does seem to produce the right output but does not seem to actually disconnect from the Internet.

Источник

Wifi doesn’t disconnect even after being removed from wifi network suggestion. How to disconnect user after removing wifi from network suggestion?

I am trying to connect and disconnect form a wifi programmatically in android(kotlin). I am able to connect user to wifi using WifiNetworkSuggestion. Now when I try to disconnect the user from the wifi(which was joined using our app WifiNetworkSuggestion), I am unable to disconnect user even after removing the user form suggestion list. Below is the code I am using :

fun disconnectFromNetwork(ssid: String, password: String) < val wifiManager: WifiManager = this.applicationContext.getSystemService( Context.WIFI_SERVICE ) as WifiManager when < Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q -> < val suggestion = WifiNetworkSuggestion.Builder() .setSsid(ssid) .setWpa2Passphrase(password) .build() val suggestionsList: MutableList= ArrayList() suggestionsList.add(suggestion) wifiManager.removeNetworkSuggestions(suggestionsList) > else -> < >> > 

removeNetworkSuggestions: Remove some or all of the network suggestions that were previously provided by the app. If one of the suggestions being removed was used to establish connection to the current network, then the device will immediately disconnect from that network.

But the wifi connection persist even after removing the wifi from suggestion. How to disconnect user after removing wifi from network suggestion?

Читайте также:  Регистратор вай фай лучший

Источник

android.net.wifi.WifiManager.removeNetworkSuggestions()

Here are the examples of the java api android.net.wifi.WifiManager.removeNetworkSuggestions() taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

3 Examples 7

// cleanup private void cleanup() < if (!ssidsToBeRemovedOnExit.isEmpty()) < ListwifiConfigList = moWiFi.getConfiguredNetworks(); for (String ssid : ssidsToBeRemovedOnExit) < for (android.net.wifi.WifiConfiguration wifiConfig : wifiConfigList) < if (wifiConfig.SSID.equals(ssid)) < moWiFi.removeNetwork(wifiConfig.networkId); >> > > if (!suggestionsToBeRemovedOnExit.isEmpty()) < moWiFi.removeNetworkSuggestions(suggestionsToBeRemovedOnExit); >// setting all members to null to avoid memory leaks channel = null; eventChannel = null; moActivity = null; moContext = null; moWiFi = null; moWiFiAPManager = null; >
// / Disconnect current Wifi. private void disconnect(Result poResult) < if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) < // noinspection deprecation moWiFi.disconnect(); >else < if (networkCallback != null) < final ConnectivityManager connectivityManager = (ConnectivityManager) moContext.getSystemService(Context.CONNECTIVITY_SERVICE); connectivityManager.unregisterNetworkCallback(networkCallback); >if (networkSuggestions != null) < moWiFi.removeNetworkSuggestions(networkSuggestions); >> poResult.success(null); >
// / Method to connect to WIFI Network private void connectTo(final Result poResult, final String ssid, final String preplacedword, final String security, final Boolean joinOnce, final Boolean withInternet) < final Handler handler = new Handler(Looper.getMainLooper()); if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) < final boolean connected = connectToDeprecated(ssid, preplacedword, security, joinOnce); handler.post(new Runnable() < @Override public void run() < poResult.success(connected); >>); > else < // error if WEP security, since not supported if (security != null && security.toUpperCase().equals("WEP")) < handler.post(new Runnable() < @Override public void run() < poResult.error("Error", "WEP is not supported for Android SDK " + Build.VERSION.SDK_INT, ""); >>); return; > if (withInternet != null && withInternet) < // create network suggestion final WifiNetworkSuggestion.Builder builder = new WifiNetworkSuggestion.Builder(); // set ssid builder.setSsid(ssid); // set preplacedword if (security != null && security.toUpperCase().equals("WPA")) < builder.setWpa2Preplacedphrase(preplacedword); >// remove suggestions if already existing if (networkSuggestions != null) < moWiFi.removeNetworkSuggestions(networkSuggestions); >// builder.setIsAppInteractionRequired(true); final WifiNetworkSuggestion suggestion = builder.build(); networkSuggestions = new ArrayList<>(); networkSuggestions.add(suggestion); if (joinOnce != null && joinOnce) < suggestionsToBeRemovedOnExit.add(suggestion); >final int status = moWiFi.addNetworkSuggestions(networkSuggestions); Log.e(WifiIotPlugin.clreplaced.getSimpleName(), "status: " + status); handler.post(new Runnable() < @Override public void run() < poResult.success(status == WifiManager.STATUS_NETWORK_SUGGESTIONS_SUCCESS); >>); > else < // Make new network specifier final WifiNetworkSpecifier.Builder builder = new WifiNetworkSpecifier.Builder(); // set ssid builder.setSsid(ssid); // set security if (security != null && security.toUpperCase().equals("WPA")) < builder.setWpa2Preplacedphrase(preplacedword); >final NetworkRequest networkRequest = new NetworkRequest.Builder().addTransportType(NetworkCapabilities.TRANSPORT_WIFI).removeCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET).setNetworkSpecifier(builder.build()).build(); final ConnectivityManager connectivityManager = (ConnectivityManager) moContext.getSystemService(Context.CONNECTIVITY_SERVICE); if (networkCallback != null) connectivityManager.unregisterNetworkCallback(networkCallback); networkCallback = new ConnectivityManager.NetworkCallback() < boolean resultSent = false; @Override public void onAvailable(@NonNull Network network) < super.onAvailable(network); if (!resultSent) < poResult.success(true); resultSent = true; >> @Override public void onUnavailable() < super.onUnavailable(); if (!resultSent) < poResult.success(false); resultSent = true; >> >; connectivityManager.requestNetwork(networkRequest, networkCallback, handler, 30 * 1000); > > >

Источник

Оцените статью
Adblock
detector