I'm developing an app, where I need a broadcast receiver which will monitor for wifi connected and disconnected states. I've tried many codes, browsed lots of stackoverflow posts, but no success. I haven't found any such method/code which work properly, some codes are not working at all, some are returning wrong info, some are making broadcast receiver crash/restart and much more. So, is there any full proof method to monitor for wifi connected/disconnected states which works for all versions of android starting from 4.0.3 Icecream sandwitch? Any help will be appreciated.
Asked
Active
Viewed 1,148 times
1 Answers
0
First, you need to define a broadcast receiver which can listen for network change event.
public class NetworkChangeReceiver extends BroadcastReceiver {
public static final String TYPE_NET_CONNECTIVITY_CHANGE = "android.net.conn.CONNECTIVITY_CHANGE";
@Override
public void onReceive(final Context context, Intent intent) {
if (TYPE_NET_CONNECTIVITY_CHANGE.equals(intent.getAction())) {
boolean connected = NetworkStatus.isNetworkConnected(context);
if (connected) {
//Connected
} else {
//Disconnected
}
}
}
}
Now register your receiver in manifest like:-
<application
...>
<receiver android:name=". NetworkChangeReceiver" >
<intent-filter>
<action android:name="android.net.wifi.WifiManager.WIFI_STATE_CHANGED_ACTION" />
<action android:name="android.intent.action.PHONE_STATE" />
</intent-filter>
</receiver>
</application>

VikasGoyal
- 3,308
- 1
- 22
- 42
-
have you checked? is it really working? I can't check as I'm out of my home today, can you please confirm the same? also, why phonestate permission? also, in onReceive, we are not listening for android.net.wifi.WifiManager.WIFI_STATE_CHANGED_ACTION then how will it respond for wifi connection/disconnection? – Feb 20 '17 at 05:02
-
I am same using in my existing application and it is working. I assume you have provided Internet permissions because without it you won't listen to any event. – VikasGoyal Feb 20 '17 at 05:11
-
Hi AVI, actually, I need to only detect that wifi is connected or disconnected, then why internet and phone permission? – Feb 20 '17 at 06:33
-
You can remove phone_state if data connection not required. – VikasGoyal Feb 20 '17 at 10:01