最近做项目的时候需要获取android设备地址,在网上找到了如下的方式

 

方式一:

import java.net.InetAddress;import java.net.NetworkInterface;import java.net.SocketException;import java.util.Enumeration;//不适用android较新版本(例如4.0等)public String getLocalIpAddress() {        try {            for (Enumeration en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {                NetworkInterface intf = en.nextElement();                for (Enumeration enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {                    InetAddress inetAddress = enumIpAddr.nextElement();                    if (!inetAddress.isLoopbackAddress()) {                        return inetAddress.getHostAddress().toString();                    }                }            }        } catch (SocketException ex) {            System.out.println(ex.toString());        }        return null;    }


但是经过测试该方法在android2.3, 2.2...较老版本有效,但是在android较新版本(例如4.0等)获取的数据不正确。

 

方式二: 通过WifiManager, DhcpInfo获取IP地址以及网关等信息(在android4.0等版本也适用)

 

package com.jason.demo.androidip;import android.content.Context;import android.net.DhcpInfo;import android.net.wifi.WifiInfo;import android.net.wifi.WifiManager;import android.text.format.Formatter;public class IPAddress {public String getIPAddress(Context ctx){WifiManager wifi_service = (WifiManager) ctx.getSystemService(Context.WIFI_SERVICE);DhcpInfo dhcpInfo = wifi_service.getDhcpInfo();WifiInfo wifiinfo = wifi_service.getConnectionInfo();System.out.println("Wifi info----->"+wifiinfo.getIpAddress());System.out.println("DHCP info gateway----->"+Formatter.formatIpAddress(dhcpInfo.gateway));System.out.println("DHCP info netmask----->"+Formatter.formatIpAddress(dhcpInfo.netmask));//DhcpInfo中的ipAddress是一个int型的变量,通过Formatter将其转化为字符串IP地址return Formatter.formatIpAddress(dhcpInfo.ipAddress);}}


加入permission


 

更多相关文章

  1. Android(安卓)如何让EditText不自动获取焦点
  2. Android(安卓)技术要点
  3. ListView点击效果设置
  4. Android(安卓)技术要点
  5. android高级应用
  6. Android使用gradle生成maven库,上传githu并使用远程maven库
  7. Android视频缩略图(二)
  8. android获取手机中的短信和,android获取手机通讯录联系人和号码
  9. android点击状态分析

随机推荐

  1. myisamchk命令使用总结
  2. Laravel - 如何为用户赋予多重角色?
  3. 从mysql中导出单个表结构和数据
  4. 无法指定目标表进行更新,在mysql中删除查
  5. mysql如何修改导入数据库文件大小限制
  6. 使用php将mysql数据导出到ODF
  7. 面试题:谈谈你对mysql的了解.
  8. PHP MYSQL 出现中文乱码的解决方案
  9. MySQL索引帮助-哪个更快?
  10. PO,Hibernate,VO,struts,spring,hibernat