Introduction to handler message mechanism and handler Mechanism
Introduction to handler message mechanism
Why handle?
When we read image information on the network, we cannot put time-consuming operations in the main thread. When we get the image message in the Child thread, we need to pass the data to the main thread.
The direct use of global variables is not feasible, because the TV _txt.setText (str) in the main thread is passed to str only after all statements are executed.
Therefore, handle is used.
Put the data obtained by the sub-thread in the message, and then process the message in handle. Because handle is called by the main thread, the message data can be updated on the home page.
1 package com. example. handlerrumen; 2 3 import android. app. activity; 4 import android. OS. bundle; 5 import android. OS. handler; 6 import android. OS. logoff; 7 import android. OS. message; 8 import android. util. log; 9 import android. widget. textView; 10 11 public class MainActivity extends Activity {12 private TextView TV _txt; 13 private Handler handler = new Handler () {14 // process messages (executed by the main thread) 15 public void handleMessage (Message msg) {16 String str = (String) msg. obj; 17 TV _txt.setText (str); 18 19 // determine whether the current function is called by the main thread. getmainlogoff () = logoff. mylogoff (); 21 // Log. d ("bh", result + ""); 22}; 23}; 24 @ Override25 protected void onCreate (Bundle savedInstanceState) {26 super. onCreate (savedInstanceState); 27 setContentView (R. layout. activity_main); 28 TV _txt = (TextView) findViewById (R. id. TV _txt); 29 // create a sub-thread and start 30 MyThread myTh = new MyThread (); 31 myTh. start (); 32} 33 // custom sub-Thread 34 class MyThread extends Thread {35 @ Override36 public void run () {37 // pseudocode to reflect 38 try {39 Thread. sleep (6000); 40 Log. d ("bh", "Access to the network"); 41 String str = "I Am a network data"; 42 // create a message object 43 Message msg = new Message (); 44 msg. obj = str; 45 // send a message 46 handler. sendMessage (msg); 47} catch (InterruptedException e) {48 e. printStackTrace (); 49} 50} 51} 52}