Just getting started with android, an android. OS. NetworkOnMainThreadException exception was reported when I wrote a Demo using Socket to communicate with the server:
Server:
Public class SimpleServer {
Public static void main (String [] args ){
Try {
ServerSocket ss = new ServerSocket (40000 );
System. out. println ("waiting for connection ......");
While (true ){
Socket s = ss. accept ();
OutputStream OS = s. getOutputStream ();
OS. write ("hello". getBytes ("UTF-8 "));
OS. close ();
S. close ();
}
} Catch (IOException e ){
// TODO Auto-generated catch block
E. printStackTrace ();
}
}
}
After asking for help, I found it was an SDK version problem. The network access in android4.0 cannot be carried out in the main program. All right, you can honestly re-open a thread:
New Thread (){
Public void run (){
Try {
Socket s = new Socket ("172.22.16.26", 40000 );
BufferedReader br = new BufferedReader (new InputStreamReader (s. getInputStream ()));
String line = br. readLine ();
Show. setText ("the server says:" + line );
Br. close ();
S. close ();
} Catch (UnknownHostException e ){
// TODO Auto-generated catch block
E. printStackTrace ();
} Catch (IOException e ){
// TODO Auto-generated catch block
E. printStackTrace ();
}
}
}. Start ();
An exception was reported:
Android. view. ViewRootImpl $ CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
I believe that you have made a very low-level mistake: operating the UI in the newly started thread is NOT thread-safe, the Android platform does not allow the newly started thread of the Activity to access the interface components of the Activity. In this case, the Handler message transmission mechanism is required:
New Thread (){
Public void run (){
Try {
Sockets s = new Socket ("172.18.6.26", 40000 );
BufferedReader br = new BufferedReader (new InputStreamReader (s. getInputStream ()));
String line = br. readLine ();
// System. out. println ("server:" + line );
Message msg = new Message ();
Msg. Why = 0x123;
Msg. obj = line;
Myhandler. sendMessage (msg );
Br. close ();
S. close ();
} Catch (UnknownHostException e ){
// TODO Auto-generated catch block
E. printStackTrace ();
} Catch (IOException e ){
// TODO Auto-generated catch block
E. printStackTrace ();
}
}
}. Start ();
Then rewrite the handlerMessage method to get the message:
Final Handler myhandler = new Handler (){
Public void handleMessage (Message msg ){
If (msg. what = 0x123 ){
System. out. println ("--------------->" + msg. obj );
Show2.setText (String) msg. obj );
}
}
};
When a new thread sends a Message, this method is automatically called. The handlerMessage (Message msg) method is still in the main thread, so you can dynamically modify the UI component.
This article is from the "on the road" blog, please be sure to keep this source http://dengxin919820.blog.51cto.com/4673187/1284971