我正在尝试使用java和xml开发一个Android应用程序,我想要一些关于如何确定应用程序所在的手机上是否启用了wifi的指导。任何帮助,将不胜感激。我尝试过使用这些方法,但他们都没有检测到我的wifi端口是正确打开还是关闭。我担心这些方法已经过时了。有没有人有最新的方法?
//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;
答案 0 :(得分:5)
通过获取WiFi系统服务的实例,可以检查WiFi的状态,如下所示:
WifiManager wifi = (WifiManager)getSystemService(Context.WIFI_SERVICE);
由此可以使用方法isWifiEnabled()
来确定是否启用了WiFi。如下:
WifiManager wifi = (WifiManager)getSystemService(Context.WIFI_SERVICE);
if (wifi.isWifiEnabled()){
//TODO: Code to execute if wifi is enabled.
}
答案 1 :(得分:0)
WiFi和移动数据都可以这样检查..
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
}
要检查任何活动的网络连接:
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();
}
答案 2 :(得分:0)
您也可以尝试获取wifi连接的wifi名称
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
}
}