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!!
Related
I have problem with WiFi connection detection. My goal is to detect when user is switching between different WiFis. I found this, but it only detects when WiFi was established. In my case I need to know when one WiFi network changed to another on phone.
You can use BroadcastReceiver
public class ConnectivityReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
ConnectivityManager conMan = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = conMan.getActiveNetworkInfo();
if(intent.getAction().equals(WifiManager.NETWORK_STATE_CHANGED_ACTION)) {
if(netInfo.isConnected()) {
WifiManager wifiManager = (WifiManager) context.getAplicationContext().getSystemService (Context.WIFI_SERVICE);
WifiInfo info = wifiManager.getConnectionInfo ();
String ssid = info.getSSID();
Log.d("Wifi Connected", "Wifi name is "+ info.getSSID());
}
}
}
}
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.
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.
I want to know whether we can make an android app which works only when we connect to a specific wi-fi Network?
All help is much appreciated! I'm all out of ideas here. Thank you.
boolean onRightNetwork() {
WifiManager wifiManager = (WifiManager) App.getContext()
.getSystemService(App.getContext().WIFI_SERVICE);
WifiInfo wifiInfo = wifiManager.getConnectionInfo();
return wifiInfo.getSSID().equals(NETWORK_NAME);
}
Run that in onResume, and just pop up a screen that says to connect to the right network if it returns false. You may also want to register a broadcast receiver to listen for wifi connect/disconnect events and perform this check as needed there as well.
You can write your own logic for that in launcher Activity.
WifiManager wifiMgr = (WifiManager) getSystemService(Context.WIFI_SERVICE);
WifiInfo wifiInfo = wifiMgr.getConnectionInfo();
String name = wifiInfo.getSSID();
above code is to get name of currently connected network name, you can make condition if it matches your predefined name, allow user to use your application.
Try this:
WifiManager wifiManager = (WifiManager)getSystemService(Context.WIFI_SERVICE);
WifiInfo wifiInfo = wifiManager.getConnectionInfo();
wifiInfo.getSSID();
After getting the SSID, match it with your desired one. If the condition is met, then do whatever you want.
You could try something like this:
ConnectivityManager connManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
if (!mWifi.isConnected()) {
// exit app here
}
make sure You have proper permission in Your AndroidManifest.xml
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission>
Related answer here: https://stackoverflow.com/a/3841407/3693617
i want to get some information about Wifi like SSID Name, ip address and speed, so i wrote this code
WifiManager wifiMgr = (WifiManager) getSystemService(WIFI_SERVICE);
WifiInfo wifiInfo = wifiMgr.getConnectionInfo();
int ip = wifiInfo.getIpAddress();
int speed = wifiInfo.getLinkSpeed();
speedString = Integer.toString(speed);
mac = wifiInfo.getMacAddress();
ssid = wifiInfo.getSSID();
ipAddress = Formatter.formatIpAddress(ip);
The problem is that if the WiFi is enabled but the phone is not connected to any network i show
SSID: 0x
Ip: 0.0.0.0
Speed: -1 mbps
I do not want to display this type of information so I tried it with
if(ipAddress=="0.0.0.0") {
Ip.setSummary("Not connected");
}
But don't work because i see the same information (ssid: 0x, ip: 0.0.0.0 ecc). How can i fix?
NetworkInfo networkInfo = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
if (networkInfo.isConnected()) {
WifiManager wifiMgr = (WifiManager) getSystemService(WIFI_SERVICE);
WifiInfo wifiInfo = wifiMgr.getConnectionInfo();
int ip = wifiInfo.getIpAddress();
int speed = wifiInfo.getLinkSpeed();
speedString = Integer.toString(speed);
mac = wifiInfo.getMacAddress();
ssid = wifiInfo.getSSID();
ipAddress = Formatter.formatIpAddress(ip);
}
Try this