Android self-taught course-simple use of Socket
Activity_main.java
1 <LinearLayout xmlns: android = "http://schemas.android.com/apk/res/android" 2 xmlns: tools = "http://schemas.android.com/tools" 3 android: layout_width = "match_parent" 4 android: layout_height = "match_parent" 5 android: orientation = "vertical" 6 tools: context = ". mainActivity "> 7 8 <EditText 9 android: id =" @ + id/editText "10 android: layout_width =" match_parent "11 android: layout_height =" wrap_content "12 android: hint = "Enter the content to be sent"/> 13 14 <Button15 android: id = "@ + id/button01" 16 android: layout_width = "match_parent" 17 android: layout_height = "wrap_content" 18 android: text = ""/> 19 20 <Button21 android: id = "@ + id/button02" 22 android: layout_width = "match_parent" 23 android: layout_height = "wrap_content" 24 android: text = "send"/> 25 26 <ScrollView27 android: layout_width = "match_parent" 28 android: layout_height = "wrap_content" 29 android: scrollbars = "vertical" 30 android: fadingEdge = "vertical"> 31 <TextView32 android: id = "@ + id/textView" 33 android: layout_width = "match_parent" 34 android: layout_height = "wrap_content" 35 android: text = "output:"/> 36 </ScrollView> 37 38 </LinearLayout>
The interface is very simple. Next we need a server and a client. Server, I use the Java Server written by Eclipse; client, I use Android Studio.
Package com. ryan. socketdemo01; import android. OS. handler; import android. OS. message; import android. support. v7.app. appCompatActivity; import android. OS. bundle; import android. util. log; import android. view. menu; import android. view. menuItem; import android. view. view; import android. widget. button; import android. widget. editText; import android. widget. textView; import android. widget. toast; import java. io. IOExcepti On; import java. io. outputStream; import java. io. unsupportedEncodingException; import java.net. socket;/*** function of this instance: the client sends data to the client (Dynamic Output Data) **/public class MainActivity extends AppCompatActivity implements View. onClickListener {private Button button01 = null; private Button button02 = null; private EditText editText = null; private TextView textView = null; private static Socket ClientSocket = null; priva Te byte [] msgBuffer = null; Handler handler = new Handler (); private void initView () {button01 = (Button) findViewById (R. id. button01); button02 = (Button) findViewById (R. id. button02); editText = (EditText) findViewById (R. id. editText); textView = (TextView) findViewById (R. id. textView); button01.setOnClickListener (this); button02.setOnClickListener (this); button01.setEnabled (true); button02.setEnab Led (false) ;}@ Override protected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); initView () ;}@ Override public void onClick (View v) {switch (v. getId () {case R. id. button01: // TODO: 15-9-4 socket connection thread connectThread (); break; case R. id. button02: // TODO: 15-9-4 data sending thread sendMsgThread (); break;} private void sendMsgThread (){ Final String text = editText. getText (). toString (); try {msgBuffer = text. getBytes ("UTF-8");} catch (UnsupportedEncodingException e) {e. printStackTrace ();} new Thread (new Runnable () {@ Override public void run () {try {OutputStream outputStream; // Socket output stream outputStream = ClientSocket. getOutputStream (); outputStream. write (msgBuffer); outputStream. flush (); outputStream. close ();} catch (IOExcep Tion e) {e. printStackTrace ();} handler. post (new Runnable () {@ Override public void run () {textView. append ("sent successfully:" + text + "\ n ");}});}}). start ();} private void connectThread () {new Thread (new Runnable () {@ Override public void run () {try {ClientSocket = new Socket ("10.0.2.2 ", 9001); if (ClientSocket. isConnected () {handler. post (new Runnable () {@ Override public void run () {textView. append (" Connection successful! "+" \ N "); button01.setEnabled (false); button02.setEnabled (true) ;});} else {handler. post (new Runnable () {@ Override public void run () {textView. append ("connection failed! "+" \ N ") ;}} 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. menu_main, menu); return true;} @ Override public boolean onOptionsItemSelected (MenuItem item) {// Handle action bar item clicks here. the action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest. xml. int id = item. getItemId (); // noinspection SimplifiableIfStatement if (id = R. id. action_settings) {return true;} return super. onOptionsItemSelected (item );}}
Here, my thread usage is:
new Thread (new Runnable) { @Override public void run() { } }
Some people on the Internet say this method is very LOW and not good, but now I only know this, and even asynctask is still learning. Another point is the sub-thread's method for updating the main UI: I use Handler. post (); it is also very simple to use.
Handler handler = new Handler (); handler. post (new Runnable () {@ Override public void run () {textView. append ("sent successfully:" + text + "\ n ");}});
I will write another blog about how several sub-threads update the main UI. I already know no more than 4 methods, but I have not done it on the fly yet.