Reputation: 195
I had a problem when i tried to return the wifi state , disconnected or connected .. well I dont get an exception but it jumps to the else {} block of my if condition, when i was debugging I found that :
NetworkInfo mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
mWifi has this: NetworkInfo: type: wifi[], state: UNKNOWN/IDLE, reason: (unspecified)
ConnectivityManager connManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
if (mWifi.isConnectedOrConnecting()){
Toast.makeText(this,"void action Working", 3).show();
}
else
{
Toast.makeText(this,"void action Not working", 3).show();
}
Upvotes: 0
Views: 2155
Reputation: 2223
You can do it this way:
final WifiManager wifiManager = (WifiManager) YourActivity.this.getSystemService(Context.WIFI_SERVICE);
if (!wifiManager.isWifiEnabled()) {
wifiManager.setWifiEnabled(true); //If it's, off turn it on.
}else{
//Do what you want to do with wi-fi.
}
Note also that I have the following permissions set in my manifest (perhaps not all of which are required in your case as I'm implementing wifi direct functionality):
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission
android:name="android.permission.ACCESS_WIFI_STATE"
android:required="true" />
<uses-permission
android:name="android.permission.CHANGE_WIFI_STATE"
android:required="true" />
<uses-permission
android:name="android.permission.INTERNET"
android:required="true" />
Upvotes: 1