Reputation: 1274
I'm trying to develop an android app with java and xml, and I would like some guidance on how to determine if wifi is enabled on the phone that the app is on or not. Any help would be appreciated. I've tried using these methods, but they all don't detect if my wifi port is open or closed correctly. I'm afraid these methods are out of date. Does anyone have an up to date method?
//determine if wifi is enabled
//1st try
wifi =Settings.Secure.getInt(cr, Settings.Secure.WIFI_ON);
//second try
wifi=Settings.Global.getInt(cr, Settings.Global.WIFI_ON, 0);
//3rd try
WifiManager wifi = (WifiManager)getSystemService(Context.WIFI_SERVICE);
if (wifi.isWifiEnabled()){
//wifi is enabled
wifiInt=1;
}
else
wifiInt=0;
Upvotes: 2
Views: 7726
Reputation: 830
Checking the state of WiFi can be done by obtaining an instance to the WiFi system service as below:
WifiManager wifi = (WifiManager)getSystemService(Context.WIFI_SERVICE);
from this, the method isWifiEnabled()
can be used to determine if WiFi is enabled. As below:
WifiManager wifi = (WifiManager)getSystemService(Context.WIFI_SERVICE);
if (wifi.isWifiEnabled()){
//TODO: Code to execute if wifi is enabled.
}
Upvotes: 9
Reputation: 124
You can also try to get wifi connected wifi name
WifiManager wifiManager = (WifiManager)HomeScreen.this.getSystemService(Context.WIFI_SERVICE);
if(wifiManager != null)
{
if(wifiManager.isWifiEnabled())
{
WifiInfo connectedWifiInfo = wifiManager.getConnectionInfo();
if(connectedWifiInfo != null)
{
if(connectedWifiInfo.getBSSID() != null)
{
// connected
}
else
{
// not connected
}
}
else
{
// not connected
}
}
else
{
// not connected
}
}
Upvotes: 0
Reputation: 1302
Both WiFi and Mobile data u can check this way..
ConnectivityManager connManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
NetworkInfo mData = connManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
if(mWifi.isConnected()||mData.isConnected()){
//Do something when data is available
}
To check for any active network connection:
private boolean isNetworkAvailable() {
//Call this method to check network connection.
ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
Upvotes: 1