Connection to specific WiFi if already have connection to another - java

I've been fighting like a fish for two days already, and I can not find a solution. I tried this code but it through time worked on Android 5(Lollipop) and didn't work at 7.1.1.(Nougat) I have another Scenario where phone loses connection and after this, it needs to return to the old Wifi.
public void setWifiConnection1(View view){
WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
WifiConfiguration wc = new WifiConfiguration();
WifiInfo wifiInfo = wifiManager.getConnectionInfo();
wc.SSID = "\"NETWORK_NAME\"";
wc.preSharedKey = "\"PASSWORD\"";
wc.status = WifiConfiguration.Status.ENABLED;
wc.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
wc.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
wc.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
wc.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
wc.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
wc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
wc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP104);
wc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
wc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
wc.priority = 999999;
wifiManager.setWifiEnabled(true);
int netId = wifiManager.addNetwork(wc);
if (netId == -1) {
netId = getExistingNetworkId(wc.SSID);
}
wifiManager.disconnect();
wifiManager.enableNetwork(netId, true);
wifiManager.reconnect();
}
private int getExistingNetworkId(String SSID) {
WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
List<WifiConfiguration> configuredNetworks = wifiManager.getConfiguredNetworks();
if (configuredNetworks != null) {
for (WifiConfiguration existingConfig : configuredNetworks) {
if (existingConfig.SSID.equals(SSID)) {
return existingConfig.networkId;
}
}
}
return -1;
}

wifiManager.setWifiEnabled(true);
You can't execute your code right after this line. You should do a wifiManager.isWifiEnabled() check and subscribe to a broadcast if it's disabled.
Next...
wifiManager.disconnect();
wifiManager.enableNetwork(netId, true);
wifiManager.reconnect();
This part is very odd: why do you disconnect ? Be aware that most of WifiManager operations are asynchronous so that's why you observe different results each time - real "disconnect" may occur after you've tried to enable your desired network.
You can always get inspiration from system API: https://android.googlesource.com/platform/frameworks/base/+/android-8.0.0_r30/wifi/java/android/net/wifi/WifiManager.java#2773
So correct sequence is:
wifiManager.addNetwork(...);
wifiManager.enableNetwork(netId, true);
wifiManager.saveConfiguration();
wifiManager.reconnect();
But if you are allowed to do so, it's more convenient to use system API directly.

Related

Using WifiManager to connect to a wireless network (wpa2)

Trying to create a NFC tag app that stores Wifi credentials on a NFC tag then read it out. From there I take the string and use that to and put the credentials through wifimanager to connect to the wireless network. I'm pretty sure I have the code correct, but it's still not connecting. Am i missing something? The channel i'm trying to connect to is WPA2.
How i'm pulling the data for the function:
#Override
public void onClick(View v)
{
String payload = _textViewData.getText().toString();
String[] parts = payload.split("-");
String SSID = parts[0];
String Password = parts[1];
part1.setText(SSID);
part2.setText(Password);
connectToWifi(SSID, Password);
}
});
UPDATED: connect function
private void connectToWifi(final String networkSSID, final String networkPassword){
if (!wifiManager.isWifiEnabled()){
wifiManager.setWifiEnabled(true);
}
WifiConfiguration conf = new WifiConfiguration();
conf.SSID = String.format("\"%s\"", networkSSID);
conf.preSharedKey = "\""+ networkPassword +"\"";
WifiManager wifiManager = (WifiManager)this.getSystemService(Context.WIFI_SERVICE);
wifiManager.addNetwork(conf);
List<WifiConfiguration> wifiList = wifiManager.getConfiguredNetworks();
for( WifiConfiguration i : wifiList ) {
if(i.SSID != null && i.SSID.equals("\"" + networkSSID + "\"")) {
wifiManager.disconnect();
wifiManager.enableNetwork(i.networkId, true);
wifiManager.reconnect();
break;
}
}
}
UPDATE 2:
I switched my network to WPA and it worked, doesn't seem to work for WPA2, is that even possible?
For connecting WPA network you need to add passphrase like this:
conf.preSharedKey = "\""+ networkPass +"\"";
For Open network you need to do this:
conf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
Then, you need to add it to Android wifi manager settings:
WifiManager wifiManager = (WifiManager)context.getSystemService(Context.WIFI_SERVICE);
wifiManager.addNetwork(conf);
after that you have to enable it.
List<WifiConfiguration> wifiList = wifiManager.getConfiguredNetworks();
for( WifiConfiguration i : wifiList ) {
if(i.SSID != null && i.SSID.equals("\"" + networkSSID + "\"")) {
wifiManager.disconnect();
wifiManager.enableNetwork(i.networkId, true);
wifiManager.status = WifiConfiguration.Status.ENABLED;
wifiManager.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
wifiManager.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
wifiManager.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
wifiManager.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP); wifiManager.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP); wifiManager.allowedProtocols.set(WifiConfiguration.Protocol.RSN); wifiManager.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
wifiManager.reconnect();
break;
}
}
Happy coding!!
Thanks #HemantParmar
With his help and a bit of googling I got it to work with WPA2:
private void connectToWifiWPA2(final String networkSSID, final String networkPassword){
WifiConfiguration conf = new WifiConfiguration();
conf.SSID = "\"" + networkSSID + "\"";
conf.preSharedKey = "\""+ networkPassword +"\"";
WifiManager wifiManager = (WifiManager)getSystemService(WIFI_SERVICE);
//if (!wifiManager.isWifiEnabled()){
// wifiManager.setWifiEnabled(true);
//}
conf.status = WifiConfiguration.Status.ENABLED;
conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
conf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
conf.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
conf.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
conf.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
int netId = wifiManager.addNetwork(conf);
wifiManager.disconnect();
wifiManager.enableNetwork(netId, true);
wifiManager.reconnect();
}

Android: How to Scan WiFi, Connect to an AP and then Establish a TCP Connection?

I am writing an Android app. In my app, I want it to scan the WiFi network, and then connect to a dedicated Access Point (AP) by checking the SSID. And then after connected to the AP, establish a TCP connection to it.
Above I have described 3 tasks in order. I know how to do each task independently, however I do not know the proper way to finish them in sequence. Examples are appreciated.
Currently my code is to start scan the WiFi network whenever the user pressed a button by:
WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
if (wifiManager.isWifiEnabled() == false) {
wifiManager.setWifiEnabled(true);
Toast.makeText(MainActivity.this, "WiFi is enabled", Toast.LENGTH_SHORT).show();
}
wifiManager.startScan();
I used a broadcast receiver to check when the scanning finished, and then invoke a method ( ReconnectAP() ) to connect WiFi to the AP. I also used the broadcast receiver to check when it connected to the AP, then I want to execute an Async Task to establish the TCP network. However, by googling, I learn that it is a bad practice to execute async task in a broadcast receiver, because the async task can be killed by Android when the receiver finished.
private String networkSSID = "The_AP_SSID";
// In onCreate of MainActivity, register the broadcast receiver:
registerReceiver(WiFireceiver, new IntentFilter(
WifiManager.NETWORK_STATE_CHANGED_ACTION));
registerReceiver(WiFireceiver, new IntentFilter(
WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
// Implement my broadcast receiver class:
BroadcastReceiver WiFireceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (WifiManager.SCAN_RESULTS_AVAILABLE_ACTION.equals(action)) {
Log.d(TAG, "WiFiReceiver received broadcast, action is SCAN_RESULTS_AVAILABLE_ACTION");
Log.d(TAG, "Start to check if need to reconnect to Charger AP");
ReconnectAP();
}
if (WifiManager.NETWORK_STATE_CHANGED_ACTION.equals(action)) {
Log.d(TAG, "WiFiReceiver received broadcast, action is NETWORK_STATE_CHANGED_ACTION");
NetworkInfo netInfo = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
// If the connection type is WiFi...
if (netInfo != null && ConnectivityManager.TYPE_WIFI == netInfo.getType()) {
// If it is connected now....
if (netInfo.isConnected()) {
Log.d(TAG, "WiFi connected");
// Get WiFi connection information, eg SSID
WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
WifiInfo wifiInfo = wifiManager.getConnectionInfo();
String ssid = wifiInfo.getSSID();
Log.d(TAG, "WiFi connected SSID is : " + ssid);
if(ssid.equals(networkSSID)) {
// Start async task to establish a TCP connection:
new ConnectTCPAsynTask().execute();
}
} else {
Log.d(TAG, "WiFi disconnected");
}
}
}
}
};
int ReconnectAP() {
Log.d(TAG, "In ReconnectAP( )");
wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
WifiInfo wifiInfo = wifiManager.getConnectionInfo();
String ssid = wifiInfo.getSSID();
Log.d(TAG, "Original connected AP SSID: " + ssid);
if (!ssid.equals(networkSSID)) {
Log.d(TAG, "It is not equal to the dedicated AP SSID,
we will disconnect the current WiFi connection,
and then connect to our dedicate AP");
List<WifiConfiguration> list = wifiManager.getConfiguredNetworks();
for (WifiConfiguration i : list) {
if (i.SSID != null && i.SSID.equals("\"" + networkSSID + "\"")) {
Log.d(TAG, "Start disconnect and reconnect to " + networkSSID);
wifiManager.disconnect();
wifiManager.enableNetwork(i.networkId, true);
wifiManager.reconnect();
return 1;
}
}
Log.d(TAG,"Reach here if cannot find the target SSID");
return -1;
}
Log.d(TAG, "Reach here if we already connected to the dedicated AP");
return 0;
}
Pass a flag from the broadcast receiver back to the main activity and let the main activity handle the task.

How to get device hotspot SSID programmatically in Android?

I'm struggling to find a way to find hotspot ssid of the device, all solutions which I found were returning Wi-Fi name to which device is connected while I want to find the hotspot name, which the device created.
getting wifi name
public static String getWifiName(Context context) {
WifiManager manager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
if (manager.isWifiEnabled()) {
WifiInfo wifiInfo = manager.getConnectionInfo();
if (wifiInfo != null) {
NetworkInfo.DetailedState state = WifiInfo.getDetailedStateOf(wifiInfo.getSupplicantState());
if (state == NetworkInfo.DetailedState.CONNECTED || state == NetworkInfo.DetailedState.OBTAINING_IPADDR) {
return wifiInfo.getSSID();
}
}
}
return null;
}

Reconnecting to a WiFi Network after disconnecting from it Programatically

I got disconnected from a WiFi network Programatically using
WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
wifi.disconnect();
DisconnectWifi discon = new DisconnectWifi();
registerReceiver(discon, new IntentFilter(WifiManager.SUPPLICANT_STATE_CHANGED_ACTION));
public class DisconnectWifi extends BroadcastReceiver {
#Override
public void onReceive(Context c, Intent intent) {
WifiManager wifi = (WifiManager) c.getSystemService(Context.WIFI_SERVICE);
if(!intent.getParcelableExtra(WifiManager.EXTRA_NEW_STATE).toString().equals(SupplicantState.SCANNING))
wifi.disconnect();
}
}
But I am not able to reconnect to the same network again. I tried reconnecting by using:
WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
wifi.reconnect();
but was not able to connect. How can I now reconnect to WiFi Network?
Thanks,
So the complete, simplified solution would look something like this:
WifiConfiguration wifiConfig = new WifiConfiguration();
wifiConfig.SSID = String.format("\"%s\"", ssid);
wifiConfig.preSharedKey = String.format("\"%s\"", key);
WifiManager wifiManager = (WifiManager)getSystemService(WIFI_SERVICE);
//remember id
int netId = wifiManager.addNetwork(wifiConfig);
wifiManager.disconnect();
wifiManager.enableNetwork(netId, true);
wifiManager.reconnect();
Hope it Helps You!!

How can I find wifi speed in Android and how can I display wifi speed in TextView?

To find wifi speed I used this code:
WifiManager wifiManager = (WifiManager)this.getSystemService(Context.WIFI_SERVICE);
WifiInfo wifiInfo = wifiManager.getConnectionInfo();
if (wifiInfo != null) {
int linkSpeed = wifiInfo.getLinkSpeed(); //measured using WifiInfo.LINK_SPEED_UNITS
//txtSpeed.setText(linkSpeed);
}
I want to display the speed in my TextView. How can I do this?
Try This ::
TextView speedcount;
String s = Integer.toString(linkSpeed);
speedcount = (TextView)findViewById(R.id.textview);
speedcount.setText(s);
txtSpeed.setText(""+linkSpeed); or textSpeed.setText(Integer.toString(linkSpeed));. Make sure txtSpeed is instantiated properly.

Categories

Resources