您的位置:首页 > 移动开发 > Android开发

转:Android 通用获取Ip的方法(判断手机是否联网的方法)

2011-03-30 10:18 931 查看
大家好,我们这一节讲一下,Android获取Ip的一些方法,在我们开发中,有判断手机是否联网,或者想获得当前手机的Ip地址,当然WIFI连接的和

我们3G卡的Ip地址当然是不一样的.

首先我尝试了如下方法:

view plain
copy to clipboard
print
?

WifiManager wifiManager = (WifiManager) getSystemService(WIFI_SERVICE);

WifiInfo wifiInfo = wifiManager.getConnectionInfo();

int
ipAddress = wifiInfo.getIpAddress();

WifiManager wifiManager = (WifiManager) getSystemService(WIFI_SERVICE);
WifiInfo wifiInfo = wifiManager.getConnectionInfo();
int ipAddress = wifiInfo.getIpAddress();


但是获得的居然是一个整数,我尝试了用些数学方法都没有成功!,所以这种方法不可取!

最后查了一些资料,发现如下方法是比较通用的,我尝试了WIFI和G3卡,都获取了争取的Ip地址:代码如下:

view plain
copy to clipboard
print
?

public
String getLocalIpAddress() {

try
{

for
(Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {

NetworkInterface intf = en.nextElement();

for
(Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {

InetAddress inetAddress = enumIpAddr.nextElement();

if
(!inetAddress.isLoopbackAddress()) {

return
inetAddress.getHostAddress().toString();

}

}

}

} catch
(SocketException ex) {

Log.e(LOG_TAG, ex.toString());

}

return

null
;

}

public String getLocalIpAddress() {
    try {
        for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
            NetworkInterface intf = en.nextElement();
            for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
                InetAddress inetAddress = enumIpAddr.nextElement();
                if (!inetAddress.isLoopbackAddress()) {
                    return inetAddress.getHostAddress().toString();
                }
            }
        }
    } catch (SocketException ex) {
        Log.e(LOG_TAG, ex.toString());
    }
    return null;
}


当我的手机处于飞行状态是,获得Ip地址为空,刚好符合要求!!!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐