Which listener does my class have to implement inorder to automatically check code if the wifi connects/disconnects?
I'm able to manually check for wifi connection/disconnection but each time I need to connect/disconnect WIFI from android settings and then run my program for the result.
My current code is as simple as:
WifiManager wifi = (WifiManager)getSystemService(Context.WIFI_SERVICE); if (wifi.isWifiEnabled()==true) { tv.setText("You are connected"); } else { tv.setText("You are NOT connected"); }
Actually you're checking for whether Wi-Fi is enabled, that doesn't necessarily mean that it's connected. It just means that Wi-Fi mode on the phone is enabled and able to connect to Wi-Fi networks.
This is how I'm listening for actual Wi-Fi connections in my Broadcast Receiver:
public class WifiReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { ConnectivityManager conMan = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo netInfo = conMan.getActiveNetworkInfo(); if (netInfo != null && netInfo.getType() == ConnectivityManager.TYPE_WIFI) Log.d("WifiReceiver", "Have Wifi Connection"); else Log.d("WifiReceiver", "Don't have Wifi Connection"); } };
In order to access the active network info you need to add the following uses-permission to your AndroidManifest.xml:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
And the following intent receiver (or you could add this programmatically...)
<!-- Receive Wi-Fi connection state changes --> <receiver android:name=".WifiReceiver"> <intent-filter> <action android:name="android.net.conn.CONNECTIVITY_CHANGE" /> </intent-filter> </receiver>
EDIT: In Lollipop, Job Scheduling may help if you're looking to perform an action when the user connects to an unmetered network connection. Take a look: http://developer.android.com/about/versions/android-5.0.html#Power
EDIT 2: Another consideration is that my answer doesn't check that you have a connection to the internet. You could be connected to a Wi-Fi network which requires you to sign in. Here's a useful "IsOnline()" check: https://stackoverflow.com/a/27312494/1140744
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With