First step: Implement socket communication.
First learn the socket programming, this is the most basic.
We use the PC to write a Java program for the server, and then write an Android app as a client, and then implement communication.
Create a new Java class as follows:
ImportJava.io.IOException;ImportJava.io.OutputStream;ImportJava.net.ServerSocket;ImportJava.net.Socket; Public class simpleserver { Public Static void Main(string[] args)throwsIOException {ServerSocket SS =NewServerSocket (30000); while(true) {Socket socket = ss.accept (); OutputStream OS = Socket.getoutputstream (); Os.write ("my email is [email protected]". GetBytes ("Utf-8")); Os.close (); Socket.close (); } }}
Click Run, if there is an exception, should be the port is occupied, open the Task Manager, the Javaw.exe terminated and then re-click Run.
The Andriod app code is as follows:
PackageCom.example.simpleclient;ImportJava.io.BufferedReader;ImportJava.io.IOException;ImportJava.io.InputStreamReader;ImportJava.net.Socket;Importandroid.support.v7.app.ActionBarActivity;ImportAndroid.os.Bundle;ImportAndroid.view.Menu;ImportAndroid.view.MenuItem;ImportAndroid.widget.TextView; Public class mainactivity extends actionbaractivity {TextView TextView;@Override protected void onCreate(Bundle savedinstancestate) {Super. OnCreate (Savedinstancestate); Setcontentview (R.layout.activity_main); TextView = (TextView) Findviewbyid (R.ID.TEXTVIEW1);NewThread () { Public void Run(){Try{Socket socket =NewSocket ("192.168.10.103",30000); BufferedReader br =NewBufferedReader (NewInputStreamReader (Socket.getinputstream ())); String line = Br.readline (); Textview.settext (line); Br.close (); Socket.close (); }Catch(IOException e) {E.printstacktrace (); }}}.start (); }@Override Public Boolean Oncreateoptionsmenu(Menu menu) {//inflate the menu; This adds items to the action bar if it is present.Getmenuinflater (). Inflate (R.menu.main, menu);return true; }@Override Public Boolean onoptionsitemselected(MenuItem Item) {//Handle Action Bar item clicks here. The Action Bar would //automatically handle clicks on the Home/up button, so long //As you specify a parent activity in Androidmanifest.xml. intid = item.getitemid ();if(id = = r.id.action_settings) {return true; }return Super. onoptionsitemselected (item); }}
The IP address inside is changed to the IP where the PC is located, the port must be the same. Install to the phone after compiling. The layout file is just a textview.
Run the app and you'll see "my email is [email protected]".
Android Network programming