Android Enterprise Development Learning--handler

Source: Internet
Author: User

I study handler is according to this way of thinking, so I also follow this idea to write: 1. What is handler? 2. What did handler do? 3. How we can use handler to achieve different functions for different scenarios                                                   ,         &N Bsp                   handler         (i) what is it?                Handler, as the name implies, is "processor", which is used to send and receive information and implement the function code according to the information matching. It contains thread queues and message queues, and the implementation of asynchronous message processing mechanisms is cleverly used in Android.         Androud starts with a primary thread (that is, the UI thread), the main thread is the UI control in the management interface, and the event is distributed in response to the customer's actions. If you need a time-consuming operation at this point, for example: to go to the Internet to download a thing, we can not put these operations in the main thread, it will easily lead to an "ARN" exception. If you put in the main thread, the interface will appear suspended animation, if 5 seconds has not been completed, you will receive an Android system error message "forced shutdown." This time we need to put these time-consuming operations on a sub-thread, because the child threads involve UI updates, the Android main thread is not secure, that is, the update UI can only be updated in the main thread, and the operations in the child threads are dangerous. At this time, Handler appeared. To solve this complex problem, because handler is running in the mainline approached (UI thread), it and the child thread can pass the data through the message object, and at this time, the handler undertakes to accept the child thread passed over ( Child threads with SENDMESSAGE () method The Message object, which contains data, puts the messages into the main thread queue and updates the UI with the main thread.                                  &NBS P                          ,         &NB Sp                         (b) What did handler do?     Handler can distribute the Message object and the Runnable object into the main thread, each handler instance is bound to the line that created it approached (typically in the main thread),      It has two functions:          (1) Arrange for messages or runnable to be executed somewhere in a main thread;        (2) Schedule an action to execute in a different thread  & nbsp;     So, to achieve the above two functions, we have to understand how to send and process based on the basis of sending and receiving information.     Some of the ways it distributes messages        post (Runnable)         Postattime (Runnable,long) & nbsp       postdelayed (Runnable long)         sendemptymessage (int)       &NBS P SendMessage (message)   Send message to message queue   &NBsp     Msg.sendtotarget ()   sending messages to Message Queuing         Sendmessageattime (Message,long) Send messages to Message Queuing         sendmessagedelayed (Message,long) delay for a certain amount of time after the message is sent to the message queue          The Post class method above allows you to arrange a runnable object into the main thread queue,        SendMessage class method, allowing you to schedule a message object with data to queue and wait for updates. (message can contain data)   knowledge supplement How does the message contain data: (1) The Message object        message object carries data, usually it uses ARG1,ARG2 to deliver the message, Of course, it can also have the obj parameter, can carry the bundle data. It is characterized by a very low system performance consumption.         Initialize: Message msg=handler.obtainmessage ();(2) Bundle object       Bundle is Android-provided class , it can be seen as a special map, a packet of key-value pairs. In particular, the keys and values must be either basic data types or arrays of basic data types (the map's key requirements are objects), and, specifically, the key requirements are string types. Use message to carry Bundle data:            put in: Msg.setdata (Bundle bundle);        & nbsp   Remove: Msg.getdata ();      Generally I use the bundle class. Code                 bundle bundle = new Bundle ();                 bundle.putint ("Myage", 21);                 bundle.putstring ("MyName", "Yummylau");                 msg.setdata (bundler);                 msg.sendtotarget ();   Code               bundle myData = Msg.getdata ();              int myage = Mydata.getint ("Myage");              String myname = mydata.getstring ("myname");   hope to be of help to everyone.              It processes the general practice of the message     The specific process of the message that needs to be in the new The Handler object uses the anonymous inner class to override the Handler Handlemessage (Message msg) method, as follows:         handler handler=new Handler () {          @Override           public void Handlemessage (Message msg)              &NBsp  //write the function code you want to execute            }         };      nbsp                          ,         &NB Sp                           (c) How we should use handler to achieve different functions for different scenarios Can          Generally we create a handler object, mainly to use handler to interact with the UI thread, Handlre can be either UI thread or new thread.     (1) Send message via handler delay to handle processing of some transactions     For example, I want to design an application to start with a welcome interface, Let this interface stop for a few seconds before jumping into a Activity home              public class Splashactivity extends activity{                      private Intent Intent;                     @Override         &NBSP ;         protected void onCreate (Bundle savedinstancestaTE) {                              //TOD O auto-generated method stubs                      super.oncrea Te (savedinstancestate);                   setcontentview ( R.layout.splash);                    startmainavtivity ();                    }            &NBS P   private void Startmainavtivity () {                    New Handler ( ). postdelayed (new Runnable) {                        &NB Sp   @Override                             PU Blic void Run () {      &NBsp                      intent = new Intent (Splashactivity.this,mainac Tivity.class);                           startactivi Ty (Intent);                            SplashActivity.this.finis H ();                       }                   }, 3000);               }               }  &nb Sp  }         The red code above uses handler to delay starting another activity.     It's worth noting that some small partners think that we started a new thread inside the main thread and then jumped the activity in the new thread. In fact, at first I also think so, in the process of learning to see a friend on the net to write the blog and test, but also reflect on a bit, ask some seniors. Just remember: There are two ways to start a new thread in Java (personal knowledge is limited), one is to use a class to inherit the thread, then instantiate to execute the start () method, and the other is to implement the Runable interface, The Runnable object is instantiated as a parameter to instantiate a thread object and then execute the start () method.     The following example is a reference to online friends: Java code  package ORG.HUALANG.HANDLERTEST3;    import android.app.Activity;  import Android.os.Bundle;  import Android.os.Handler;  import Android.util.Log;    public class HandlerTest3 extends Activity {     private Handler Handler = new Handler () ;      Private String TAG = "System.out";      @Override      public void onCreate (Bundle savedinstancestate) {     &N Bsp   Super.oncreate (savedinstancestate);          Handler.post (R);          Setcontentview (R.layout.main);         //thread t = new Thread (r);         //t.start ();                    LOG.D (TAG, "Activity ID:" +thread.currentthread (). GetId ());          LOG.D (TAG, "Activity Name:" +thread.currentthread (). GetName ());               }      Runnable r = new Runnable ()      {         public void run ()          {     &nbs P       LOG.D (TAG, "Handler ID:" +thread.currentthread (). GetId ());              LOG.D (TAG, "Handler Name:" +thread.currentthread (). GetName ());              try {                 Thread . Sleep (5000);             } catch (Interruptedexception e) {         &NBSP ;      //TODO auto-generated catch block                  E.PR Intstacktrace ();             }         }     };  }   running results prove to be two basis for the same thread: ①activity IDor name and handler ID or name are the same ② set up            handler.post (R);           setcontentview (R.layout.main), that is, if the text message is displayed immediately after execution, it can be shown that they are not on the same thread, but the actual situation is to perform the handler 5 seconds before displaying the text information, Note that they are on the same thread if the code is changed to             handler.post (R);             setcontentview (R.layout.main);             thread t = new Thread (r);              T.start ();   executes again, running the result as follows, starting the thread through start, they are not on the same line approached (2) uses handler to send a message, and then different threads accept and process the message. Obviously, we're using handler in Android more to implement what we want in asynchronous threads     I break handler processing into two ways:   1 builds handler on the UI thread, Send information by a non-UI thread the UI thread accepts information; (for updating the UI) code: Run Result: This example is similar to the one above, but not the same as the thread established with handler. The above example is more limited, because we do not have to write in the project in the same file, if we are in different files to get the same handler object, we can consider using the "constructor" method, the handler object as a parameter to pass, you can implement different files of the public , or we can define it as static.  android In fact gave us a class handlerthread, the class encapsulated Looper and MessageQueue (after the personal test that, if not, please point out OH). The example is a rewrite of the example above that the non-UI thread handles messages sent by the UI thread. DirectOn the code: Run the result: from the example, the effect is basically the same as the previous example, less looper.prepare () and Looper.loop (); I am not familiar with this class, please the great God pointing twos.      When using handler, just keep in mind that handler is in which thread establishes the thread on which the post executes, handlerui the difference between threading and non-UI threading, and performing certain actions at timed times. will be able to master the basic. Android Async threads can also use Asynctask to perform asynchronous tasks. The underlying implementation is also based on handler.   Original address: http://www.360doc.com/content/14/0108/13/7673502_343568991.shtml

Android Enterprise Development Learning--handler

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.