Android Network Programming

Source: Internet
Author: User

1. Obtain Network Information

First, add the permission to androidmanifest. xml.

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

The Code is as follows:

public class MainActivity extends Activity {TextView netWorkTextView;ConnectivityManager cManager;NetworkInfo networkInfo;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);netWorkTextView = (TextView)findViewById(R.id.networkInfo);cManager = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);}@Overrideprotected void onStart(){super.onStart();networkInfo = cManager.getActiveNetworkInfo();netWorkTextView.setText(networkInfo.toString());}}

Displayed in: indicates that the Wi-Fi connection is used.

 

2. Socket network communication

1) server: Create an android project socketserverdemo.

public class MainActivity extends Activity {@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);startService(new Intent(this,SocketService.class));}}

Socketservice class

public class SocketService extends Service{Thread mServiceThread;Socket client;@Overridepublic IBinder onBind(Intent intent) {// TODO Auto-generated method stubreturn null;}@Overridepublic void onCreate(){super.onCreate();mServiceThread = new Thread(new SocketServerThread());}public class SocketServerThread extends Thread {private static final int PORT = 8801;private SocketServerThread() {}@Overridepublic void run() {// TODO Auto-generated method stubtry {ServerSocket serverSocket = new ServerSocket(PORT);while(true){System.out.println("begin client connected");client = serverSocket.accept();System.out.println("client connected");BufferedReader reader = new BufferedReader(new InputStreamReader(client.getInputStream()));System.out.println("read from client:");String textLine = reader.readLine();if (textLine.equalsIgnoreCase("EXIT")) {System.out.println("EXIT invoed, closing client");break;}System.out.println(textLine);PrintWriter writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(client.getOutputStream())));writer.println("ECHO from server: " + textLine);writer.flush();writer.close();reader.close();}} catch (IOException e) {// TODO: handle exceptionSystem.err.println(e);}}}}

 

2) Client: Create a socketclientdemo for the android Project

Public class mainactivity extends activity {Private Static final string serverip = "192.168.1.100"; // your PC's ipprivate static final int SERVERPORT = 8801; textview mmsgrev; edittext mmsgedit; button mmsgsendbtn; string msendmsg; string mreceivedmsg; @ overrideprotected void oncreate (bundle savedinstancestate) {super. oncreate (savedinstancestate); setcontentview (R. layout. activity_main); mmsgrev = (textview) Fin Dviewbyid (R. id. receive_msg); mmsgedit = (edittext) findviewbyid (R. id. edit_msg); mmsgsendbtn = (button) findviewbyid (R. id. send_msg); mmsgsendbtn. setonclicklistener (new view. onclicklistener () {@ overridepublic void onclick (view v) {// todo auto-generated method stubsocket socket = NULL; msendmsg = mmsgedit. gettext (). tostring (); try {socket = new socket (serverip, SERVERPORT); printwriter writer = new printw Riter (New bufferedwriter (New outputstreamwriter (socket. getoutputstream (); writer. println (msendmsg); writer. flush (); bufferedreader reader = new bufferedreader (New inputstreamreader (socket. getinputstream (); mreceivedmsg = reader. readline (); If (mreceivedmsg! = NULL) {mmsgrev. settext (mreceivedmsg);} else {mmsgrev. settext ("receive data error");} writer. close (); reader. close (); socket. close ();} catch (unknownhostexception e) {// todo: handle exceptionlog. I ("error", E. getmessage ();} catch (ioexception e) {// todo: handle exceptionlog. I ("error", E. getmessage ());}}});}}

The client runs on my tablet, and the server runs on my mobile phone. Then, enter the text in the text box on the server and click the send button. The message is received.

Note: The port numbers of both programs are the same. The client IP address is the IP address of my computer. Both programs must have the permission.

<uses-permission android:name="android.permission.INTERNET" ></uses-permission>

Reference: socket-Based Network Communication

 

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.