Handler asynchronous message processing mechanism
Asynchronous Message processing in Android mainly consists of four parts: Message, Handler, MessageQueue and Looper.
Message: responsible for inter thread message delivery
Handler: used to send and receive information
MessageQueue: the queue used to store messages. Each thread has only one such object
Looper: used to continuously monitor the existence of messages in the queue and take them out
Direct instance code
Display an increasing number every second
public class MainActivity extends AppCompatActivity { private static final int UPDATE=0x1; private int flag = 0; private TextView text; private Handler handler=new Handler() { @Override public void handleMessage(Message msg) { switch (msg.what) { case UPDATE: text.setText(String.valueOf(msg.arg1)); break; } } }; private Runnable thread=() -> { while (true) { try { Thread.sleep(1000); Message msg = new Message(); msg.what = UPDATE; msg.arg1 = flag++; handler.sendMessage(msg); } catch (InterruptedException e) { e.printStackTrace(); } } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); text = (TextView)findViewById(R.id.text); Thread thread1 = new Thread(thread); thread1.start(); } }
The same function can be achieved by using the timer provided by the Handler
public class MainActivity extends AppCompatActivity { private static final int UPDATE=0x1; private int flag = 0; private TextView text; private Handler handler = new Handler(); private Runnable thread= new Runnable() { public void run() { handler.postDelayed(this, 1000); text.setText(String.valueOf(flag++)); } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ButterKnife.bind(this); text = (TextView)findViewById(R.id.text); handler.post(thread); } }