Use handler and thread threads in Android to perform background operations

Source: Internet
Author: User

Disclaimer: This article is in reference to "decrypt Google Android" and the Android Video tutorial (www.mars-droid.com).

As we all know, the application on the PC when need to do some complex data operation, but do not need UI UI, we will dedicate a thread to the application to perform these complex data operations. Through threading, you can perform time-consuming operations such as data processing, data download, and no impact on the user's interface. In Android application development, you will also encounter such problems. When we need to access the network, download the data from the Internet and display it on our UI, we start the background thread to download the data, and the download thread executes and returns the result to the main user interface thread.

For threading control, we will introduce a handler class that allows you to queue multiple tasks running in different threads and use the message and Runnable objects to schedule these tasks. In Javadoc, this explains handler: handler can send and process message objects or runnable objects, which are associated with a line runnable. Each instance of handler is associated with a thread and a thread's message queue. When a handler object is created, a thread or message queue is also created, and the handler object sends and processes these messages or runnable objects.

Here are a few ways to construct a handler object:

A, if new is a handler object without a parameter constructor, then this handler will automatically be associated with the current run line threads, that is, the handler will use the same message queue as the currently running thread, and the messages in that queue can be processed.

Private Handler Handler = new Handler ();

In this experiment, we create an handler object with an parameterless constructor in the main user interface, which pushes a runnable object to the message queue and prints the current thread ID in the run function of the Runnable object. We compare the main user interface thread ID with the runnable thread ID. The specific code is as follows:

HandlerTest01

The output from this example can be found to be the same as the ID of the Runnable object and the main user interface thread. In this example, we post a Runnable object directly using the handler object, which is equivalent to calling the run function of the Runnable object directly, and saying that run () is not called by the start function, then a new thread is not created. Instead, the run () method is called directly inside the original thread, so the output thread ID is the same.

b, if new is a handler object with a parameter constructor, then the handler object will be associated with the Looper represented by the parameter. Note: At this point the thread class should be a special class Handlerthread class, a thread class of the Looper class, which inherits from the thread class.

Handlerthread handlerthread = new Handlerthread ("MyThread"); Handlerthread.start ();
Private MyHandler handler = new MyHandler (Handlerthread.getlooper ());

Class MyHandler extends Handler {
Public MyHandler () {

}

Public MyHandler (Looper Looper) {
Super (Looper);
}
}

The following example shows how to open a new thread and process the message through handler.

Handlertest02.java

Based on the results returned by this example, it can be seen that the new thread ID differs from the thread ID of the main user interface. Because we called the Thread.Start () method, we really created a new thread that was in a different thread context than the original thread, so the print output had a different thread ID.

C, if you need to handler the object to process the message, then you will overload the handler class Handlemessage function.

Private Handler Handler = new Handler () {

@Override
public void Handlemessage (Message msg) {
Todo:handle the MSG
Usually we update UI here.
}
}

Note The comments section, which we typically handle in Handlemessage to update the UI interface.

The basic use of the handler class is described earlier, but the thread class is still not involved. To implement a new thread in the background and take some time-consuming actions through that thread, we also use the thread class to do this. Let's start with an example program that uses the thread class.

Threadtest.java

The results of this program execution are as follows. When the new thread creates an object, it passes in an object of the Runnable class, overloads the Run () method in the Runnable object, executes the time-consuming operation, and the new thread instance executes the Start method, opening a new thread to execute the Runnable's Run method.

These are the methods that I now have access to thread execution, in which we can do what we need to do (such as downloading, processing data, detecting network status, etc.) and separating it from the UI interface, then the UI interface will not be blocked because of the time-consuming operation.

In the book "Decrypting Google Android," a model of such a startup thread was found. Using this model, we can put some time-consuming operations into the Dostuff method, and in the Updateuihere method to update the UI interface, you can complete the functionality required by a thread. The other instructions are written in the comments section.

Handler MyHandler = new Handler () {
public void Handlemessage (Message msg) {
Updateuihere ();
}
}

New Thread () {
public void Run () {
Dostuff (); Perform time-consuming operations
Message msg = Myhandler.obtainmessage ();
Bundle B = new bundle ();
B.putstring ("Key", "value");
M.setdata (b); To add data to a message
Myhandler.sendmessage (m); Send a message to handler to update the UI
}
}.start ();

Use handler and thread threads in Android to perform background operations

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.