Android的......怎么找出来,如果我在一个wifi上网? [英] Android ... how to find out if I'm on a wifi internet?
本文介绍了Android的......怎么找出来,如果我在一个wifi上网?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在我的应用程序只需要知道,如果设备连接到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;
}
这篇关于Android的......怎么找出来,如果我在一个wifi上网?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文