Android手机获取IP地址的两种方法
本文章讲解了WIFI和GPRS两种情况下获取手机IP地址的方法
1.使用WIFI
1,首先设置用户权限 AndroidManifest.xml添加:
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"></uses-permission>
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE"></uses-permission>
<uses-permission android:name="android.permission.WAKE_LOCK"></uses-permission>
2,在 MainActivity.xml 中加入如下:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//获取wifi服务
WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
//判断wifi是否开启
if (!wifiManager.isWifiEnabled()) {
wifiManager.setWifiEnabled(true);
}
WifiInfo wifiInfo = wifiManager.getConnectionInfo();
int ipAddress = wifiInfo.getIpAddress();
String ip = intToIp(ipAddress);
EditText et = (EditText)findViewById(R.id.EditText01);
et.setText(ip);
}
private String intToIp(int i) {
return (i & 0xFF ) + "." +
((i >> 8 ) & 0xFF) + "." +
((i >> 16 ) & 0xFF) + "." +
( i >> 24 & 0xFF) ;
}
3.布局文件activity_main.xml
<EditText
android:id="@+id/EditText01"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
2.使用GPRS
1,首先,设置用户上网权限 AndroidManifest.xml
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
2,其次
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;
}