当前位置: 代码迷 >> Android >> Android学习之取得ip地址
  详细解决方案

Android学习之取得ip地址

热度:94   发布时间:2016-05-01 16:42:38.0
Android学习之获得ip地址
package cn.net;import java.net.InetAddress;import java.net.NetworkInterface;import java.net.SocketException;import java.util.Enumeration;import android.app.Activity;import android.content.Context;import android.net.wifi.WifiInfo;import android.net.wifi.WifiManager;import android.os.Bundle;import android.util.Log;import android.widget.EditText;public class IpUtil extends Activity {    /** Called when the activity is first created. */    @Override    public void onCreate(Bundle savedInstanceState) {            super.onCreate(savedInstanceState);            setContentView(R.layout.main);                        //获取wifi服务            WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);            //判断wifi是否开启            if (!wifiManager.isWifiEnabled()) {             wifiManager.setWifiEnabled(true);               }             //使用wifi获得有问题,可能要真机测试            WifiInfo wifiInfo = wifiManager.getConnectionInfo();                  int ipAddress = wifiInfo.getIpAddress();              String ip = intToIp(ipAddress);              EditText et = (EditText)findViewById(R.id.EditText01);            EditText e2=(EditText)findViewById(R.id.editText2);            String ip2=getLocalIpAddress();            et.setText(ipAddress);            e2.setText(ip2);        }            //初始化为0.0.0.0        private String intToIp(int i) {                                return (i & 0xFF ) + "." +                  ((i >> 8 ) & 0xFF) + "." +                  ((i >> 16 ) & 0xFF) + "." +                  ( i >> 24 & 0xFF) ;         }      //这个可用,    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("WifiPreference IpAddress", ex.toString());             }             return null;         }     }

?

  相关解决方案