How to Be Notified on Wifi Network Status Change

How to get notifications for Network change(Connect,Disconnect,Change)

Look at this official Apple documentation

Using Reachability you can recognize the type of your connection.

There is also a complete example on how detect the changes and the documentation is updated now for ARC.

I hope this can help you

How to get notified when the users Wifi changes from one network to other

  • Write a BroadcastReceiver as follows

    public class TheBroadcastReceiver extends BroadcastReceiver 
    {
    @Override
    public void onReceive(Context context, Intent intent)
    {
    WifiManager wifiManager = (WifiManager) context
    .getSystemService(Context.WIFI_SERVICE);
    NetworkInfo datainfo = intent
    .getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
    if (datainfo != null)
    {
    if (datainfo.getType() == ConnectivityManager.TYPE_WIFI)
    {
    //have different network states here
    if (datainfo.getState() == datainfo.State.CONNECTING || datainfo.getState() == datainfo.State.CONNECTED) {
    //work accordingly
    }
    }
    }
    }
    }
  • Register a BroadcastReceiver and register these entries at manifest

        <receiver android:name="yours package details like com.a.b.c.TheBroadcastReceiver " >
    <intent-filter>
    <action android:name="android.net.wifi.supplicant.CONNECTION_CHANGE" />
    <action android:name="android.net.wifi.STATE_CHANGE" />
    </intent-filter>
    </receiver>
  • Add following permission sets at manifest

      <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
    <uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
  • Also visit http://developer.android.com/training/monitoring-device-state/connectivity-monitoring.html

Wifi-Network Changed Notification

If you are using this Reachability files then its easy.
Add an Observer inside the viewWillAppear

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reachabilityDidChange:) name:kReachabilityChangedNotification object:nil];

And implement the observer method

- (void)reachabilityDidChange:(NSNotification *)notification {
Reachability *reachability = (Reachability *)[notification object];

if ([reachability isReachable] && [reachability isReachableViaWiFi]) {
NSLog(@"Reachable via Wifi");
}
}

Updated

Add the following code inside the Network change completion block of your Reachability handler. By Sending the SCNetworkReachabilityFlag as a parameter to the method.

-(BOOL)isReachableViaWiFi :(SCNetworkReachabilityFlags)flags {

// Check we're reachable
if((flags & kSCNetworkReachabilityFlagsReachable))
{
// Check we're NOT on WWAN
if((flags & kSCNetworkReachabilityFlagsIsWWAN))
{
return NO;
}
return YES;
}
return NO;
}

Detecting Network Connectivity Changes using Reachability, NSNotification and Network Link Conditioner in Swift

You must create a Reachability object before you can receive notifications from it. Also, be sure to call the startNotifier() method on the Reachability object you create. This would be an example of how to do so inside of your application delegate:

class AppDelegate: UIResponder, UIApplicationDelegate
{
private var reachability:Reachability!;

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: NSDictionary?) -> Bool
{
NSNotificationCenter.defaultCenter().addObserver(self, selector:"checkForReachability:", name: kReachabilityChangedNotification, object: nil);

self.reachability = Reachability.reachabilityForInternetConnection();
self.reachability.startNotifier();
}

@objc func checkForReachability(notification:NSNotification)
{
// Remove the next two lines of code. You cannot instantiate the object
// you want to receive notifications from inside of the notification
// handler that is meant for the notifications it emits.

//var networkReachability = Reachability.reachabilityForInternetConnection()
//networkReachability.startNotifier()

let networkReachability = notification.object as Reachability;
var remoteHostStatus = networkReachability.currentReachabilityStatus()

if (remoteHostStatus.value == NotReachable.value)
{
println("Not Reachable")
}
else if (remoteHostStatus.value == ReachableViaWiFi.value)
{
println("Reachable via Wifi")
}
else
{
println("Reachable")
}
}
}

I recommend you take a look at the documentation for NSNotificationCenter and NSNotification. That way you'll be more familiar with how to work with notifications next time something like this comes up.

Swift 3

NotificationCenter.default.addObserver(self, selector:Selector(("checkForReachability:")), name: NSNotification.Name.reachabilityChanged, object: nil)
let reachability: Reachability = Reachability.forInternetConnection()
reachability.startNotifier()

Is there a NSNotificationCenter Notification for WiFi network changes?

Not to my knowledge. I would use CoreWLAN to get a list of all WiFi interfaces on the system, and then monitor their status using the SystemConfiguration framework.

Here's a command-line example (error checking niceties elided, ARC required):

#import <Foundation/Foundation.h>
#import <CoreWLAN/CoreWLAN.h>
#import <SystemConfiguration/SystemConfiguration.h>

void wifi_network_changed(SCDynamicStoreRef store, CFArrayRef changedKeys, void *ctx)
{
[(__bridge NSArray *)changedKeys enumerateObjectsUsingBlock:^(NSString *key, NSUInteger idx, BOOL *stop)
{
/* Extract the interface name from the changed key */
NSString *ifName = [key componentsSeparatedByString:@"/"][3];
CWInterface *iface = [CWInterface interfaceWithName:ifName];

NSLog(@"%@ status changed: current ssid is %@, security is %ld",
ifName, iface.ssid, iface.security);
}];
}

int main(int argc, char *argv[])
{
/* Get a list of all wifi interfaces, and build an array of SCDynamicStore keys to monitor */
NSSet *wifiInterfaces = [CWInterface interfaceNames];
NSMutableArray *scKeys = [[NSMutableArray alloc] init];
[wifiInterfaces enumerateObjectsUsingBlock:^(NSString *ifName, BOOL *stop)
{
[scKeys addObject:
[NSString stringWithFormat:@"State:/Network/Interface/%@/AirPort", ifName]];
}];

/* Connect to the dynamic store */
SCDynamicStoreContext ctx = { 0, NULL, NULL, NULL, NULL };
SCDynamicStoreRef store = SCDynamicStoreCreate(kCFAllocatorDefault,
CFSTR("myapp"),
wifi_network_changed,
&ctx);

/* Start monitoring */
SCDynamicStoreSetNotificationKeys(store,
(__bridge CFArrayRef)scKeys,
NULL);

CFRunLoopSourceRef src = SCDynamicStoreCreateRunLoopSource(kCFAllocatorDefault, store, 0);
CFRunLoopAddSource([[NSRunLoop currentRunLoop] getCFRunLoop],
src,
kCFRunLoopCommonModes);
[[NSRunLoop currentRunLoop] run];
}

Broadcast Receiver get notified when connecting to another wifi network

Please try this solution,

BroadcastReceiver broadcastReceiver = new WifiBroadcastReceiver();

IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(WifiManager.SUPPLICANT_STATE_CHANGED_ACTION);
context.registerReceiver(broadcastReceiver, intentFilter);

You need to check the MAC addresses of the routers to check if there is a change in the Wifi connection.

public class WifiBroadcastReceiver extends BroadcastReceiver {

@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (WifiManager.SUPPLICANT_STATE_CHANGED_ACTION .equals(action)) {
SupplicantState state = intent.getParcelableExtra(WifiManager.EXTRA_NEW_STATE);
if (SupplicantState.isValidState(state)
&& state == SupplicantState.COMPLETED) {
boolean changed = checkWifiChanged();
}
}
}

/** Detect if WiFi is changed. */
private boolean checkWifiChanged() {
boolean changed = false;

// You can store the previous MAC address in Shared Preferences and fetch it here
String previousMacAddress = getPreviousMacAddress();

WifiManager wifiManager =
(WifiManager) context.getSystemService(Context.WIFI_SERVICE);

WifiInfo wifi = wifiManager.getConnectionInfo();
if (wifi != null) {
// Get current router MAC address
String bssid = wifi.getBSSID();
changed = !previousMacAddress.equals(bssid);
}

return changed;
}
}

You can store the previous MAC address in a database or Shared Preference and check the new connected MAC address with the previous one. If they are different, then the WiFi connection has changed otherwise not.



Related Topics



Leave a reply



Submit