As we all know, applications on PCs that require complex data operations, but do not require interface UI, will write a thread for the application to perform these complex data operations. With threads, you can perform time-consuming operations such as data processing, data downloads, and no impact on the user's interface. In Android application development, the same problem can be encountered. When we need to access the network, download the data from the Internet and display it on our UI, we start a background thread to download the data and return the results to the main user interface thread after the download thread finishes executing.
For thread control, we'll introduce a handler class that allows you to queue multiple tasks running on different threads and schedule them with the message and Runnable objects. In Javadoc, this is explained to handler: handler can send and process message objects or runnable objects, which are associated with a line threads relative. Each handler instance is associated with a thread and a thread's message queue. When a handler object is created, a thread or message queue is created at the same time, and the handler object sends and processes the messages or runnable objects.
Here are a few ways to construct a handler object that need to be understood:
A, if new is a handler object of an parameterless constructor, then the handler will automatically be associated with the current run line threads relative, that is, the handler will use the same message queue as the currently running thread and can process the messages in that queue.
private Handler handler = new Handler();
We do an experiment in the main user interface to create a handler object with an parameterless constructor that pushes a Runnable object to the message queue and prints the current thread Id in the Runnable object's run function. We compare the primary user interface thread ID with the runnable thread ID. The specific code is as follows:
HandlerTest01
public class HandlerTest01 extends activity {
@Override
public void OnCreate (Bundle savedinstancestate) {
Super.oncreate
(savedinstancestate);
Setcontentview (R.layout.main);
SYSTEM.OUT.PRINTLN ("Activity--->" + thread.currentthread (). GetId ());
Handler.post (R);
}
Private Handler Handler =
new Handler ();
Private Runnable R = new Runnable () {
@Override
public void Run () {
try {
Thread.Sleep (2000);
catch (Interruptedexception e) {
TODO auto-generated Catch block
E.printstacktrace ();
}
System.out.println
("Runnalbe--->" + thread.currentthread (). GetId ());
}
};
}