Handler's understanding and use 1. Handler's understanding and use

Source: Internet
Author: User

Handler's understanding and use 1. Handler's understanding and use

Directory:

 

Basic knowledge:

 

1. Android process and thread model

2. Main Android UI thread (or thread security issues)

Knowledge points:

Handler Introduction

Handler Method 1: The subthread processes the transaction (working in the background). After the task is finished, the subthread sends a message through handler to notify the UI thread to update the UI control, the handleMessage of the handler in the main thread processes the UI update action.

Handler usage Method 2: Handler + HandlerThread

 

 

 

Basic knowledge:

1. Android process and thread model

Every Android application runs in a user process with an independent user ID to ensure that the data and programs of each application are isolated from each other.

Reference: http://www.cnblogs.com/Hendy2014/articles/android_process_model.html

2. Main Android UI thread (or thread security issues)

What is the main UI thread? What is the single-thread model of Android? What is Android thread security?

Refer:

Http://www.cnblogs.com/yaozhenfa/p/np_android_Handler.html

Http://www.cnblogs.com/dawei/archive/2011/04/09/2010259.html

 

Knowledge points:
Android. OS. Handler, android. OS. Handler. Callback
Logoff,
Thread, Runnable
Message and Message queue

 

Handler Introduction

Because of the preceding Android process model and thread model (UI main thread and thread security issues), Android provides some solutions. Handler is one of them.

Explanation: When an application is started, Android will first enable a main thread (that is, the UI thread). The main thread is the UI control in the management interface for event distribution. For example, if you click a Button, Android will distribute the event to the Button to respond to your operation. If you need a time-consuming operation, such as reading data online or reading a large local file, you cannot put these operations in the main thread, if you put it in the main thread, the interface will be suspended. If the process is not completed in five seconds, you will receive an error message "Force disable" from the Android system ". at this time, we need to put these time-consuming operations in a sub-thread. Because the sub-thread involves UI update, the main Android thread is thread insecure, that is, updating the UI can only be updated in the main thread. Operations in the Child thread are dangerous. at this time, Handler came up to solve this complicated problem. Because Handler runs in the main thread (in the UI thread), it and the sub-thread can transmit data through the Message object, at this time, Handler is responsible for receiving the Message object (containing data) transmitted by the subthread using the sedMessage () method ), put these messages into the main thread queue and update the UI with the main thread. (From: http://www.cnblogs.com/dawei/archive/2011/04/09/2010259.html)

Handler has two message methods to solve inter-thread communication and operation problems. One is Handler. sendMessage () series, Handler. post (Runnble) series of methods, but in-depth Handler source code, will find that is the same thing.

 

Handler Method 1: The subthread processes the transaction (working in the background). After the task is finished, the subthread sends a message through handler to notify the UI thread to update the UI control.In the main threadHandleMessage of handler processes the UI update action.

 

, Handler post is asynchronous
, Two queues, post thread-to-column, message queue

Handler usage method 1 model Diagram

Public class HandlerTestActivity extends Activity {private TextView TV; private static final int UPDATE = 0; private Handler handler = new Handler () {@ Override public void handleMessage (Message msg) {// TODO receives the message and updates the control content on the UI thread if (msg. what = UPDATE) {// Bundle B = msg. getData (); // TV. setText (B. getString ("num"); TV. setText (String. valueOf (msg. obj);} super. handleMessage (msg) ;}};/** Called when the activity is first created. * // @ Override public void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. main); TV = (TextView) findViewById (R. id. TV); new Thread () {@ Override public void run () {// send a message to handler for receiving in the TODO child Thread, update TextView value by handler try {for (int I = 0; I <100; I ++) {Thread. sleep (500); Message msg = new Message (); msg. what = UPDATE; // Bundle B = new Bundle (); // B. putString ("num", "updated value:" + I); // msg. setData (B); msg. obj = "updated value:" + I; handler. sendMessage (msg) ;}} catch (InterruptedException e) {e. printStackTrace ();}}}. start ();}}

  

In addition, the post () method is used as an example.

Package android. handler; 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 HandlerTest extends Activity {/** Called when the activity is first created. */private Button startButton; private Button endButton; @ Override public void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. main); // obtain the control object startButton = (Button) findViewById (R. id. startButton); endButton = (Button) findViewById (R. id. endButton); // sets the listener startButton for the control. setOnClickListener (new StartButtonListener (); endButton. setOnClickListener (new EndButtonListener ();} class StartButtonListener implements OnClickListener {public void onClick (View v) {// call the post () method of Handler, put the thread object to be executed in the queue handler. post (updateThread) ;}} class EndButtonListener implements OnClickListener {public void onClick (View v) {// call the removeCallbacks () method of Handler to delete the unexecuted thread Object handler in the queue. removeCallbacks (updateThread) ;}// create a Handler Object Handler handler = new Handler (); // create a new thread object Runnable updateThread = new Runnable () {// write the operation to be executed in the run method of the thread object public void run () {System. out. println ("updateThread"); // call the postDelayed () method of Handler. // the function of this method is to put the thread object to be executed into the queue. After the time ends, run the specified thread object // The first parameter is of the Runnable type: the thread object to be executed // The second parameter is of the long type: the delay time, in milliseconds. handler. postDelayed (updateThread, 3000 );}};}

 

Handler usage Method 2: Handler + HandlerThread

It is equivalent to enabling an asynchronous thread by using the encapsulated HandlerThread. It contains its own logoff object, that is, the MessageQueue message mechanism running in the asynchronous thread. When creating a Handler, The HandlerThread is used. the getlomessage () method obtains the Looper and uses it as a parameter created by handler to bind it to the Handler. In this way, the handler message is processed (handleMessage or post runnable method) it is in the handlerThread of the asynchronous thread.

Sample Code 1:

Public class ThreadDemo extends Activity {private static final String TAG = "bb"; private int count = 0; private Handler mHandler; private Runnable mRunnable = new Runnable () {public void run () {// For ease of viewing, Log is used to print the Log. e (TAG, Thread. currentThread (). getId () + "" + count); count ++; // setTitle ("" + count); // execute mHandler every 2 seconds. postDelayed (mRunnable, 2000) ;};@ Override public void onCreate (Bundle savedInstanceState) {Log. e (TAG, "Main id" + Thread. currentThread (). getId () + "" + count); super. onCreate (savedInstanceState); setContentView (R. layout. main); // start the thread HandlerThread handlerThread = new HandlerThread ("threadone") through Handler; handlerThread. start (); mHandler = new Handler (handlerThread. getLooper (); mHandler. post (mRunnable) ;}@ Override protected void onDestroy () {// remove the thread from the current handler. removeCallbacks (mRunnable); super. onDestroy ();}}

 

When a handler is created, if the logoff object (new Handler (loler) or setloler (loler) is not specified for it, the handler uses the Logoff of the thread that created it by default, then, the handler message processing will eventually run in the thread where it was created (the runnable object in post () and the handleMessage () code after sendMessage, in the following example, if the main UI thread is used to create a handler, the runnable object in the post () and the handleMessage () code after sendMessage () will all run in the main UI thread.

Example 1:

Public class ThreadDemo extends Activity {private static final String TAG = "bb"; private int count = 0; private Handler mHandler; private Runnable mRunnable = new Runnable () {public void run () {// For ease of viewing, Log is used to print the Log. e (TAG, Thread. currentThread (). getId () + "" + count); count ++; setTitle ("" + count); // execute mHandler every 2 seconds. postDelayed (mRunnable, 2000) ;};@ Override public void onCreate (Bundle savedInstanceState) {Log. e (TAG, "Main id" + Thread. currentThread (). getId () + "" + count); super. onCreate (savedInstanceState); setContentView (R. layout. main); // start the thread mHandler = new Handler (); mHandler. post (mRunnable); // mRunnable will eventually run on the UI main thread} @ Override protected void onDestroy () {// unbind the thread from the current handler // mHandler. removeCallbacks (mRunnable); super. onDestroy ();}}

 

----------------------

Check for missing traps: java thread Review

Create a Thread in the main thread and start (). Different threadids are printed for the same runnable (). The thread after start enters the Thread state machine, and the cpu time slice is executed when the thread is started, then enter the Start, Run, pause, stop, and other state machines. (Do you still remember the thread lifecycle ?)

Private Runnable mRunnable = new Runnable () {public void run () {// Log is printed to facilitate viewing. e (TAG, Thread. currentThread (). getId () + "" + count); count ++; setTitle ("" + count); // execute mHandler every 2 seconds. postDelayed (mRunnable, 2000) ;};@ Override public void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. main); // start Thread thread Thread = new thread (mRunnable) through Handler; Thread. start ();}

  

Related blog posts:

Http://www.cnblogs.com/youxilua/archive/2011/11/25/2263825.html

Http://www.cnblogs.com/yaozhenfa/p/np_android_Handler.html

 

Other references:

The Handler described in this book Pro android 3 is very detailed.

 

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.