Android 通用获取Ip的方法   编辑文档    学分 +2 大家好,我们这一节讲一下,Android获取Ip的一些方法,在我们开发中,有判断手机是否联网,或者想获得当前手机的Ip地址,当然WIFI连接的和  我们3G卡的Ip地址当然是不一样的.  首先我尝试了如下方法:  view plaincopy to clipboardprint?  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 plaincopy to clipboardprint?  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) {  Log.e(LOG_TAG, ex.toString());  }  return null;  }  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) {  Log.e(LOG_TAG, ex.toString());  }  return null;  }  当我的手机处于飞行状态是,获得Ip地址为空,刚好符合要求!!!  希望对大家有所帮助!谢谢~

更多相关文章

  1. 浅谈Java中Collections.sort对List排序的两种方法
  2. Python list sort方法的具体使用
  3. python list.sort()根据多个关键字排序的方法实现
  4. Android(安卓)常用控件讲解
  5. Android中startService的使用及Service生命周期
  6. Android事件分发机制完全解析,带你从源码的角度彻底理解(上)
  7. 【Android(安卓)界面效果42】如何自定义字体
  8. 2011.06.07(2)——— android 调试android源码包下的package应用的
  9. android RxJava(RxAndroid)的简单使用

随机推荐

  1. android Criteria
  2. 【转】Android输入法框的梳理
  3. Android实现关机重启的方法分享
  4. Caused by: java.lang.ClassCastExceptio
  5. Android(安卓)Timer使用的异常:Timer was
  6. android viewflipper 左右滑动切换显示图
  7. 使用NotificationCompat获得好看的通知 (
  8. [置顶] Eclipse及常用插件安装下载地址
  9. ANDROID 隐藏 任务栏 systemui systembar
  10. Android(安卓)Layout之三:Linear Layout