The Android development tutorial is handle to implement multithreading and asynchronous processing _android

Source: Internet
Author: User
Tags event listener message queue stub

This is a brief talk about handler, why is there handler this functional characteristics? First of all, the basic controls are basically called and processed in the OnCreate (Bundle savedinstancestate) method of the activity, but in some cases, such as downloading software on the network, some operations that need to wait for a longer response time, If the same method of activity, then in the implementation of the method, the whole activity is not moving, the user can only wait, such a user experience is very poor, this approach brings the best result is waiting for a while, get the desired results, The bad situation is to wait for a long time, there is no result, and some even make the activity error, in order to avoid these circumstances, so introduced the characteristics of handler, he is like a thread queue, it is also a kind of asynchronous message processing.

First, let's take a look at an example to understand the handler.

The layout file is two buttons, start and stop, respectively, to control the start and end of the thread.

Copy Code code as follows:

<button
Android:id= "@+id/start"
android:layout_height= "Wrap_content"
Android:layout_width= "Fill_parent"
android:text= "@string/start"
/>
<button
Android:id= "@+id/stop"
android:layout_height= "Wrap_content"
Android:layout_width= "Fill_parent"
android:text= "@string/stop"
/>

The code in the activity is as follows:

Copy Code code as follows:

Import android.app.Activity;
Import Android.os.Bundle;
Import Android.os.Handler;
Import Android.view.View;
Import Android.view.View.OnClickListener;
Import Android.widget.Button;

public class Handlerdemo1activity extends activity {
Button Startbutton = null;
Button Endbutton = null;
Handler Handler = new Handler ();
/** called the activity is a. */
@Override
public void OnCreate (Bundle savedinstancestate) {
Super.oncreate (savedinstancestate);
Setcontentview (R.layout.main);
Startbutton = (Button) Findviewbyid (R.id.start);
Startbutton.setonclicklistener (New Startlistener ());
Endbutton = (Button) Findviewbyid (r.id.end);
Endbutton.setonclicklistener (New Endlistener ());
}

Class Startlistener implements onclicklistener{

@Override
public void OnClick (View arg0) {
TODO auto-generated Method Stub
Handler.post (Handlerthread);
}

}

Class Endlistener implements onclicklistener{
@Override
public void OnClick (View arg0) {
TODO auto-generated Method Stub
Handler.removecallbacks (Handlerthread);
}

}

Runnable handlerthread = new Runnable () {

@Override
public void Run () {
TODO auto-generated Method Stub
System.out.println ("Handlerthread is Running ...");
Handler.postdelayed (Handlerthread, 3000);
}
};
}

We can see that the event listener is bound to two buttons in the activity, an instance of handler is created, and an anonymous inner class is created, a thread handlerthread that implements the Runnable interface.

When the Start button is pressed, the Handler.post (handlerthread) is executed; This code, as I said before, handler a thread queue, which means that the handlerthread thread is added to the handler thread queue Because the Handlerthread is the first thread, so it executes its run () method immediately. In the Run () method, handler.postdelayed (Handlerthread, 3000), and handlerthread into the handler thread queue again, set a delay of 3000ms. In this way, the entire program runs continuously and prints "Handlerthread is Running ..." every 3000ms in Logcat.

However, it is worth noting that, do not think that the present handler, so that these printing operations are the thread and the main threads separate, in fact, there is no two threads running, these printed content, but also the main thread ran out. We can experiment with the OnCreate function and print the name of the current thread through the Thread.currentThread.getName (), you can see, are the same, are main, This means that the main thread is running out. We know that the start of a thread requires a start () method, and that the Handlerthread is not started in this program, but instead calls the run () method directly. So it's no surprise that the main thread is running.

From the example above, this handler, if used in this way, is not the effect we want, because it does not implement Asynchrony or runs in a main thread.

So we have to use handler in a different way.
To implement handler asynchronous multithreading, you need to understand the other two classes, one is the message class and the other is the Looper class.
Each handler object has a message queue in which the message object is stored, and obtainmessage () can be used to obtain it. At the same time, the message object is used to pass the use, it can pass two integers and an object, try to use the message arg1 and arg2 two integral type to pass the parameter, so the system consumes the smallest (API says), if the amount of data transfer is large, you can use the SetData (Bundle a), where the Bundle object can be roughly viewed as a map object, but its key is string, and value is a limited number of types that can be viewed in the API.

The Looper class has the ability to iterate over messages from message queues, and we can use Looper in a thread so that the thread can loop through the message queue and know that the message queue is empty. But we generally do not directly create and use Looper, in the Android provided by the Handlerthread class, the implementation of the Looper function, so we just use the Handlerthread class can be, We use the Handlerthread object to invoke Getlooper () to get the Looper object of the thread.

Let's look at the following example

Copy Code code as follows:

Import android.app.Activity;
Import Android.os.Bundle;
Import Android.os.Handler;
Import Android.os.HandlerThread;
Import Android.os.Looper;
Import Android.os.Message;

public class Handlerdemo2activity extends activity {
/** called the activity is a. */
@Override
public void OnCreate (Bundle savedinstancestate) {
Super.oncreate (savedinstancestate);
Setcontentview (R.layout.main);
System.out.println ("activity---->" +thread.currentthread () GetName ());
Handlerthread handlerthread = new Handlerthread ("Handlerthread");//Create a Handlerthread object, which is a thread
Handlerthread.start ()//Start thread

MyHandler MyHandler = new MyHandler (Handlerthread.getlooper ());//Create a MyHandler object that inherits handler, as you can see from the following MyHandler class , the constructor for the handler (Looper looper) of the handler parent class is invoked, and the Looper object that is passed in here is obtained from the Handlerthread.
Message msg = Myhandler.obtainmessage ();//Get Messages Object
Msg.sendtotarget ()//sends the resulting message object to the handler that generated the message, MyHandler, when MyHandler receives the message, it calls its Handlemessage method to process the message
}

Class MyHandler extends handler{
Public MyHandler () {//constructors
TODO auto-generated Constructor stub
}

Public MyHandler (Looper looper) {//constructor
Super (Looper);//implements the constructor of the parent class
}

@Override
public void Handlemessage (msg) {//When this handler receives the message object, this method is automatically invoked to process the message object
TODO auto-generated Method Stub
System.out.println ("Handler---->" +thread.currentthread (). GetName ());
}
}
}

The above code in the Logcat System.out execution result is:
acitivity---->main
Handler---->handlerthread
This shows that the use of handler, combined with Looper and message, can be implemented with the main thread separation, so that multithreading and asynchronous processing can be implemented.

Related Article

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.