最近做项目的时候需要获取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<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) {            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

<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>


更多相关文章

  1. android里发送mail的几种方式
  2. Android加载/处理超大图片神器!
  3. Android】获取Mac地址
  4. webview开发-适配多分辨率的Android设备
  5. 【Android(安卓)应用开发】GitHub 优秀的 Android(安卓)开源项目
  6. Android序列化
  7. Eclipse Android(安卓)project name有错误, source tree无红叉解
  8. 同步、更新、下载Android(安卓)Source & SDK from 国内镜像站
  9. Android10共享文件总是读取不到文件,文件资源不存在!

随机推荐

  1. Android(安卓)Studio一些常用的快捷键
  2. android小游戏模版—重力感应
  3. 介始一下Android(安卓)单元测试框架类---
  4. android jpush(极光推送)快速集成
  5. android apk 防止反编译技术第三篇-加密a
  6. android通过oauth1.0发表新浪微博
  7. Android中提供的HttpURLConnection和Http
  8. Android(安卓)Intent机制实例详解(1)
  9. 【Android】修改App字体的三种方法.md
  10. Android中 @id 与 @+id 区别