由网友(回忆回忆、回不去的记忆)分享简介:在我的应用程序只需要知道,如果设备连接到WIFI网络或没有。我觉得这个功能适用于仿真器,但不是在真实的设备。 In my application I just need to know if the device is connected to wifi network or not. I think this fu...
在我的应用程序只需要知道,如果设备连接到WIFI网络或没有。我觉得这个功能适用于仿真器,但不是在真实的设备。
In my application I just need to know if the device is connected to wifi network or not. I think this function works on emulator but not on real device.
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(),还是我只是把'这个'(我打电话从服务的功能)。
And which context do I use here? getAplicationContext() or getBaseContext() or do I just put 'this' (I'm calling the function from a Service).
推荐答案
试试这个:
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;
}
您也可以使用相同的移动类型:
You can also use the same for the mobile type:
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;
}
相关推荐
最新文章