Android development enhancement (1) ----- obtain a local IP Address

Source: Internet
Author: User

I. Overview
I am used to network programming in Linux. I have been wondering how to get the IP address of my mobile phone before I use a smartphone ). Okay, I know that Android is based on the Linux kernel. Can I use the network programming method in Linux I learned to get the IP address? In fact, this is a relatively low-level method. on Android, Java APIs can be fully used for implementation, and the implementation code is very simple. The following implementation can only obtain the local IP address (intranet IP address), excluding the Internet IP address. If you want to obtain the Internet IP address, use other methods.
 
II. Implementation
Create a new project GetIp, modify the/res/layout/main. xml file, and add a TextView text in it. The complete main. xml file is as follows:
1 <? Xml version = "1.0" encoding = "UTF-8"?>
2 <LinearLayout xmlns: android = "http://schemas.android.com/apk/res/android"
3 android: orientation = "vertical"
4 android: layout_width = "fill_parent"
5 android: layout_height = "fill_parent"
6>
7
8 <TextView
9 android: id = "@ + id/nametextview"
10 android: layout_width = "fill_parent"
11 android: layout_height = "wrap_content"
12 android: text = ""
13 android: textSize = "20px"
14/>
15
16 <TextView
17 android: id = "@ + id/ipTextView"
18 android: layout_width = "fill_parent"
19 android: layout_height = "wrap_content"
20 android: text = ""
21 android: textSize = "20px"
22/>
23
24 </LinearLayout>

Next, modify GetIp. A java file is used to declare a ConnectivityManager object and a NetworkInfo object, and write a dialog box function. When a user runs the program without opening the network, the dialog box prompts the user to check the network. The complete GetIp. java file is as follows:
 
1 package com. nan. getip;
2
3 import android. app. Activity;
4 import android. app. AlertDialog;
5 import android. content. DialogInterface;
6 import android.net. ConnectivityManager;
7 import android.net. NetworkInfo;
8 import android. OS. Bundle;
9 import java.net. InetAddress;
10 import java.net. NetworkInterface;
11 import java. util. Enumeration;
12 import java.net. SocketException;
13 import android. util. Log;
14 import android. widget. TextView;
15
16
17 public class GetIp extends Activity
18 {
19 private TextView ipTextView = null;
20 private TextView nameTextView = null;
21 // define a ConnectivityManager object
22 private ConnectivityManager mConnectivityManager = null;
23 // define a NetworkInfo object
24 private NetworkInfo mActiveNetInfo = null;
25
26/** Called when the activity is first created .*/
27 @ Override
28 public void onCreate (Bundle savedInstanceState)
29 {
30 super. onCreate (savedInstanceState );
31 setContentView (R. layout. main );
32
33 nameTextView = (TextView) findViewById (R. id. nametextview );
34 ipTextView = (TextView) findViewById (R. id. ipTextView );
35 // instantiate the mConnectivityManager object
36 mConnectivityManager = (ConnectivityManager) getSystemService (CONNECTIVITY_SERVICE); // gets the system Connection Service
37 // instantiate the mActiveNetInfo object
38 mActiveNetInfo = mConnectivityManager. getActiveNetworkInfo (); // obtain network connection information
39 if (mActiveNetInfo = null)
40 myDialog ();
41 else
42 setUpInfo ();
43
44}
45
46 // obtain the local IP address Function
47 public String getLocalIPAddress ()
48 {
49 try
50 {
51 for (Enumeration <NetworkInterface> mEnumeration = NetworkInterface. getNetworkInterfaces (); mEnumeration. hasMoreElements ();)
52 {
53 NetworkInterface intf = mEnumeration. nextElement ();
54 for (Enumeration <InetAddress> enumIPAddr = intf. getInetAddresses (); enumIPAddr. hasMoreElements ();)
55 {
56 InetAddress inetAddress = enumIPAddr. nextElement ();
57 // if it is not a loop address
58 if (! InetAddress. isLoopbackAddress ())
59 {
60 // directly return the local IP Address
61 return inetAddress. getHostAddress (). toString ();
62}
63}
64}
65}
66 catch (SocketException ex)
67 {
68 Log. e ("Error", ex. toString ());
69}
70 return null;
71}
72
73 // display IP information
74 public void setUpInfo ()
75 {
76 // For a Wi-Fi network
77 if (mActiveNetInfo. getType () = ConnectivityManager. TYPE_WIFI)
78 {
79 nameTextView. setText ("network type: WIFI ");
80 ipTextView. setText ("IP Address:" + getLocalIPAddress ());
81}
82 // for mobile phone networks
83 else if (mActiveNetInfo. getType () = ConnectivityManager. TYPE_MOBILE)
84 {
85 nameTextView. setText ("network type: Mobile Phone ");
86 ipTextView. setText ("IP Address:" + getLocalIPAddress ());
87}
88 else
89 {
90 nameTextView. setText ("network type: Unknown ");
91 ipTextView. setText ("IP Address :");
92}
93
94}
95
96 // display dialog box
97 private void myDialog ()
98 {
99 AlertDialog mDialog = new AlertDialog. Builder (GetIp. this)
100. setTitle ("NOTE ")
101. setMessage ("the current network is unavailable. Check the network! ")
102. setPositiveButton ("OK", new DialogInterface. OnClickListener ()
103 {
104
105 @ Override
106 public void onClick (DialogInterface dialog, int which)
107 {
108 // TODO Auto-generated method stub
109 // close the dialog box
110 dialog. dismiss ();
111 // end the Activity
112 GetIp. this. finish ();
113}
114 })
115. create (); // create this dialog box
116 mDialog. show (); // This dialog box is displayed.
117}
118
119}

Finally, modify the AndroidManifest. xml file and add two permissions to it:
 
<Uses-permission android: name = "android. permission. INTERNET"> </uses-permission>
<Uses-permission android: name = "android. permission. ACCESS_NETWORK_STATE"> </uses-permission>

Okay. Run the program directly without opening the network. The prompt is displayed:

 

 

Open the network and then run the program:

 

Okay.

From lknlfy
 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.