Setting UI issues in Threads:
Android is a security concern, and it is forbidden to operate on the UI of the sub-thread Squadron system, so it needs to be handled by handler.
In child threads, the handler class is implemented when UI-related operations are required.
1. Create the handler in the main thread, its function is to listen to MSG, when the MSG received some action
Public Handler Mhandler = new Handler () {public void Handlemessage (Message msg) {switch (Msg.what) {...}}}
2. Send msg in the child thread:
New Thread (New Runnable () {public void run () {try {mhandler.obtainmessage (1). Sendtotarget (); Thread.Sleep (<span style= "White-space:pre" ></SPAN>}} catch (Exception e) {//TODO auto-generated Catch Blocke.printstacktrace ();}}}). Start ();
Achieve the effect of long press the button to perform the operation continuously:
In this example, when a button is long pressed, the phone continues to send a command over TCP
public void Hookmove (final activity activity, final String Cmd,motionevent event) {if (event.getaction () = = Motionevent.ac Tion_down) {Toast.maketext (activity, "hook begins to move", Toast.length_short). Show (); longclicked = true; Thread t = new Thread () {@Overridepublic void run () {super.run (); while (longclicked) {//Send command Tcpcontrol.sendcmd (cmd); try { Thread.Sleep (250);} catch (Interruptedexception e) {e.printstacktrace ();}}}; T.start ();} else if (event.getaction () = = motionevent.action_up) {Toast.maketext (activity, "hook stops Moving", Toast.length_short). Show (); longclicked = false; System.out.println ("Action_up");}}
Hookup.setontouchlistener (New Ontouchlistener () {@Overridepublic Boolean onTouch (View V, motionevent event) {//TODO Auto-generated Method stubcmd = "n" + strhookselected + "3"; Hookmove (activity, CMD, event); return true;});
Determine the connection status of the phone's socket server:
Compared to the system-provided isconnected functions, it is better to simulate the ping operation in Linux (http://blog.csdn.net/yudajun/article/details/10062339)
The code function sends a ping command to the specified IP and, if successful, proves that the socket is in a connected state
private static Boolean startping (String IP) {Boolean success = false; Process p = null;try {p = runtime.getruntime (). EXEC ("Ping-c 1-i 0.2-w 1" + IP); int status = P.waitfor (); if (status = = 0) {success = true;} else {success = false;}} catch (Exception e) {success = false;} finally {P.destroy ();} return success;}
Android thread Squadron UI to operate, Button long press to achieve continuous Send command effect, detect socket and server connection status