在我的应用程序中,我只需要知道设备是否连接到wifi网络。我认为这个功能适用于模拟器,但不适用于真实设备。
public static boolean wifiInternet(Context c)
{
try
{
ConnectivityManager connectivityManager = (ConnectivityManager)c.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo ni = connectivityManager.getActiveNetworkInfo(); // CRASHES HERE
String name = ni.getTypeName();
if(name.equals("WIFI"))
return true;
else
return false;
}
catch(Exception e)
{
return false;
}
}
我在这里使用哪种上下文? getAplicationContext()或getBaseContext()或者我只是把'this'(我从服务中调用函数)。
答案 0 :(得分:12)
试试这个:
public boolean isUsingWiFi() {
ConnectivityManager connectivity = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo wifiInfo = connectivity
.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
if (wifiInfo != null && wifiInfo.getState() == NetworkInfo.State.CONNECTED
|| wifiInfo.getState() == NetworkInfo.State.CONNECTING) {
return true;
}
return false;
}
您也可以将此功能用于移动设备类型:
public boolean isUsingMobileData() {
ConnectivityManager connectivity = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo mobileInfo = connectivity
.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
if (mobileInfo != null && mobileInfo.getState() == NetworkInfo.State.CONNECTED
|| mobileInfo.getState() == NetworkInfo.State.CONNECTING) {
return true;
}
return false;
}