Google banned network access in the main thread after the 4.0 system because:
The main thread is responsible for the UI response. If network access is performed on the main thread, force shutdown is triggered for more than 5 seconds. Therefore, such time-consuming operations cannot be placed in the main thread. Put it in the Child thread, and the Child thread cannot change the UI of the main thread, so Handler is introduced. Handler is defined in the main thread and used in the child thread.
Handler definition of the main thread:
Handler loginHandler = new Handler () {public void handleMessage (Message msg) {isNetError = msg. getData (). getBoolean ("isNetError"); System. out. println (isNetError); if (proDialog! = Null) {proDialog. dismiss ();} if (isNetError) {Toast. makeText (LoginActivity. this, "Logon Failed: \ n1. please check your network connection. \ n2. please contact us! ", Toast. LENGTH_LONG ). show () ;}// incorrect username and password else {Toast. makeText (LoginActivity. this, noticeMsg, Toast. LENGTH_LONG ). show (); // clear the previous SharePreferences password clearSharePassword ();}}};The subthread used to log on to the main thread:
// Open a Thread for Logon verification. It is mainly used for failure and is successfully switched directly to Thread loginThread = new Thread (new LoginFailureHandler () through startAcitivity (Intent); loginThread. start ();
The use of Handler in sub-threads:
/*** Login handler * @ author wangfeng * @ date 2013-12-19 09:25:42 **/class LoginFailureHandler implements Runnable {@ Overridepublic void run () {/* userName = userNameEdit. getText (). toString (); password = loginPasswordEdit. getText (). toString (); * // verification address String validateURL = url + "/login"; boolean loginState = validateLocalLogin (userNameEdit. getText (). toString (), loginPasswordEdit. getText (). toString (), validateURL); Log. d (this. toString (), "validateLogin"); // login successful // test --- start loginState = true; // --- test end if (loginState) {// you need to transmit data to the login interface. Intent intent = new Intent (); intent. setClass (LoginActivity. this, ListViewActivity. class); Bundle bundle = new Bundle ();/* bundle. putString ("MAP_USERNAME", userNameEdit. getText (). toString (); intent. putExtras (bundle); * // redirects to the proDialog page after logon. dismiss (); startActivity (intent);} else {// notify the UI main thread to update the UI by calling handler, Message message = new Message (); bundle bundle = new Bundle (); bundle. putBoolean ("isNetError", isNetError); message. setData (bundle); loginHandler. sendMessage (message );}}}Use the messgae. setData method to bring Budle into the bucket, and then use Handler. sendMessage to put the message in the bucket. process it in handlerMessage of Handler.