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

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

首先我尝试了如下方法:

view plain copy to clipboard print ?
  1. WifiManagerwifiManager=(WifiManager)getSystemService(WIFI_SERVICE);
  2. WifiInfowifiInfo=wifiManager.getConnectionInfo();
  3. int ipAddress=wifiInfo.getIpAddress();
复制 打印
  1. WifiManagerwifiManager=(WifiManager)getSystemService(WIFI_SERVICE);
  2. WifiInfowifiInfo=wifiManager.getConnectionInfo();
  3. int ipAddress=wifiInfo.getIpAddress();

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

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

view plain copy to clipboard print ?
  1. public StringgetLocalIpAddress(){
  2. try {
  3. for (Enumeration<NetworkInterface>en=NetworkInterface.getNetworkInterfaces();en.hasMoreElements();){
  4. NetworkInterfaceintf=en.nextElement();
  5. for (Enumeration<InetAddress>enumIpAddr=intf.getInetAddresses();enumIpAddr.hasMoreElements();){
  6. InetAddressinetAddress=enumIpAddr.nextElement();
  7. if (!inetAddress.isLoopbackAddress()){
  8. return inetAddress.getHostAddress().toString();
  9. }
  10. }
  11. }
  12. } catch (SocketExceptionex){
  13. Log.e(LOG_TAG,ex.toString());
  14. }
  15. return null ;
  16. }
复制 打印
  1. public StringgetLocalIpAddress(){
  2. try {
  3. for (Enumeration<NetworkInterface>en=NetworkInterface.getNetworkInterfaces();en.hasMoreElements();){
  4. NetworkInterfaceintf=en.nextElement();
  5. for (Enumeration<InetAddress>enumIpAddr=intf.getInetAddresses();enumIpAddr.hasMoreElements();){
  6. InetAddressinetAddress=enumIpAddr.nextElement();
  7. if (!inetAddress.isLoopbackAddress()){
  8. return inetAddress.getHostAddress().toString();
  9. }
  10. }
  11. }
  12. }catch (SocketExceptionex){
  13. Log.e(LOG_TAG,ex.toString());
  14. }
  15. return null ;
  16. }

当我的手机处于飞行状态是,获得Ip地址为空,刚好符合要求!!!

希望对大家有所帮助!谢谢~

更多相关文章

  1. Android Studio之工程中导入jni库方法
  2. Android取消EditText自动聚焦、自动弹出输入法的方法
  3. 转-Android Studio *.jar 与 *.aar 的生成与*.aar导入项目方法
  4. Android IPC机制(二):AIDL的基本使用方法
  5. Android 实现图片的自动缩放,适应分辨率不同的手机
  6. 在PC端进行android截屏的多种方法
  7. Android应用程序模拟手机按键
  8. Android在线更新SDK的方法(使用国内镜像)

随机推荐

  1. android 输出.txt 文本换行问题
  2. Android(安卓)重启应用代码
  3. android自动检测版本更新
  4. Writing a Hello-world Android(安卓)NDK
  5. targetSdkVersion 23以下6.0中调用checkS
  6. Android(安卓)onDestroy防止WebView内存
  7. Android之键盘点击事件
  8. Android(安卓)Pull Refresh View
  9. android 图片高斯模糊
  10. Android(安卓)SDK 目录和作用的分析详解