1. Use WIFI
First, set user permissions.
Xml Code
- <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>
Second, the Code is as follows:
Java code
- Public void onCreate (Bundle savedInstanceState ){
- Super. onCreate (savedInstanceState );
- SetContentView (R. layout. main );
- // Get the wifi Service
- WifiManager wifiManager = (WifiManager) getSystemService (Context. WIFI_SERVICE );
- // Determine whether wifi is enabled
- 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 );
- }
2. Use GPRS
First, set the user's Internet Access Permissions
Xml Code
- <Uses-permission android: name = "android. permission. INTERNET"> </uses-permission>
Second, the Code is as follows:
Java code
- 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;
- }