Aggregate Knowledge Android Android part of 2020 articles Handler

 

1. What is Handler?

  Handler is associated with a corresponding thread can be sent and processed by the Message and Runnable object MessageQueue. Usually we think it is an asynchronous mechanism.

  a. may make the corresponding Message Runnable and corresponding treatment in the future at some point.

  b. I want to make time-consuming operation is completed in sub-thread, allowing the operator to update the UI is completed in the main thread, and the communication between the child thread and the main thread is done by Handler.

2.Handler to use

  Handler provides many methods asynchronous mechanism, but we will only post and commonly used method sendMessage series, we take a look at the constructor Handler provides it:

  • Handler (): The default constructor of this handler with Looper for the current thread.
  • Handler (Handler.Callback callback): The constructor of this handler for the current thread Looper, and accept a callback interface, where you can process the message.
  • Handler (Looper looper): Looper using the supplied instead of the default.
  • Handler (Looper looper, Handler.Callback callback): Use Looper provided instead of the default, but rather accept a callback interface to handle the message.

  Next we take a look at various ways to provide it Handler:

  • post (Runnable r): Runnable r leads to add the message queue.
  • postAtTime (Runnable r, long uptimeMillis): Runnable r so added to the message queue, and uptimeMillis.
  • postDelayed (Runnable r, long delayMillis): Runnable r is added to make the message queue, and runs after the specified time elapses.
  • removeCallbacks (Runnable r): Delete all messages Runnable tasks that can be run in the message queue.
  • removeMessages (int what): Delete the message queue message object what field is "what" of the message task.
  • sendEmptyMessage (int what): sends an empty message object, the message and what the empty set value.
  • sendEmptyMessageAtTime (int what, long uptimeMillis): sending a message containing only the values ​​to be delivered at a particular time.
  • sendEmptyMessageDelayed (int what, long delayMillis): sending a message that only contains the values ​​to be delivered after a specified time interval.
  • sendMessage (Message msg): push the end of the message queue of the message, the completion of all pending messages before the current time.
  • sendMessageAtTime (Message msg, long uptimeMillis): Before uptimeMillis before (in milliseconds), put the message in the message queue of all pending messages in the absolute time.
  • sendMessageDelayed (Message msg, long delayMillis): before, after all pending messages (the current time + delayMillis), a message into the message queue.

3.Handler internal implementation mechanism

  When the interview, Handler asked principles of probability is still quite large, not only just to interview, and we need to look at the principles Handler, then Handler to use for our purposes is very good, at least we know that we sent how to send a message to the UI thread, when problems arise, we analyze just a little will know where the problem occurred, and then fix it, well, not much gossip pulled, to introduce the following implementation principles Handler mechanism.
  Handler mechanism can also be called asynchronous message mechanism, which is mainly composed of four parts: Message, Handler, MessageQueue, Looper , on top of that we have access to the Message Handler and, the next focus of our understanding of four members:

1.Message
  the Message is the message passing between threads, which can carry a small amount of information within, for exchanging data between different threads. The Message of arg1 and arg2 can carry int data type using Object obj can carry data.

2.Handler
  Handler handler name suggests is meant, as long as it is used to send messages Message objects in the child thread, the UI thread processing the message subject Message, the thread of the call sendMessage method of sending a message Message objects, and messages sent through a series of ground after removed eventually be transmitted to the Handler handleMessage method, the final message object is processed in the message handleMessage process.

3.MessageQueue
  the MessageQueue meaning is the message queue, as long as it is used to store all messages sent over by Handler. This part of the message would have been stored in the message queue them, waiting to be processed. Each thread will have a MessageQueue objects, remember these words. As can be seen from the fact, literally, the MessageQueue underlying data structure is a queue and the queue is stored only Message object.

4.Looper
  Looper is MessageQueue housekeeper each thread after the call Looper loop () method, will enter into an infinite loop which, and in the presence of a message whenever MesssageQueue, these messages will be removed Looper, and pass it to the Handler of the handleMessage (method). Each thread Looper is only one object.

  Learn the four members of the above-mentioned Handler mechanism, we come to the idea of ​​reason again: first in the UI thread we create a Handler instance of an object, whether it is anonymous inner classes and custom classes generated Handler instance of an object, we need to handleMessage methods rewritten in handleMessage methods we accept the logic can be written to process messages after UIi thread through parameters msg, then we create a child thread, the child thread needs to update the UI, create a new message object, and the message data recorded within the message object message, such arg1, arg2, obj, etc., and sends out the message instance object calls sendMessge method by the foregoing Handler instance of the object, then the message is stored in MessageQueue waiting to be processed, this MessageQueue housekeeper when Looper is constantly present in the message MessageQueue taken out, by callback method dispatchMessage pass the message to the Handler handleMessage method, the aforementioned message will eventually be removed from the MessageQueue Looper passed to the method handleMessage , It will eventually be processed. This is the mechanism Handler entire workflow, how? do you understand? Consider the following chart you will know better the:

Handler mechanisms work flow chart

From the perspective of the source code to understand the principles Handler: http://blog.csdn.net/u012827296/article/details/51236614

4.Handler cause a memory leak and solutions

The reason: non-static inner classes held by an anonymous quote outer class, resulting in external activity can not be released.

Solution: The internal handler holds weak references outside and the handler instead of static inner classes, call the removeCallback handler () method in the activity of onDestory () in.

http://blog.csdn.net/javazejian/article/details/50839443

5. How Handler allows for communication between the child and the child thread thread?

  Today's interview, Handler basically a lot of the interviewer will say it smooth, but if you want to highlight the interviewer, then we need to understand the Handler's very thorough, we usually code is a sub-thread asynchronous communication with the main thread, so between the child and the child thread thread can it? Of course you can, but we need to know enough about Looper, in-depth study Hanlder you can see the author Handler source code analysis section. So if we need child threads Handler communication between threads A and sub-B, and is the child thread A sends a message to the child thread B, then what should we do?

public class MainActivity extends AppCompatActivity { private Handler threadHandler; [@Override](https://my.oschina.net/u/1162528) protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } class ThreadA extends Thread{ [@Override](https://my.oschina.net/u/1162528) public void run() { super.run(); Looper.prepare(); threadHandler = new Handler(){ [@Override](https://my.oschina.net/u/1162528) public void handleMessage(Message msg) { super.handleMessage(msg); //收到来自于ThreadB的消息,注意这里运行在ThreadA线程中 //...... } }; Looper.loop(); } } class ThreadB extends Thread{ [@Override](https://my.oschina.net/u/1162528) public void run() { super.run(); Looper looper = Looper.myLooper(); Message message = new Message(); message.obj = "ThreadB发送消息到ThreadA"; //...... threadHandler.sendMessage(message); } } } 

  I wrote this code is probably not good, but it does not matter, we just need to learn a few key areas, how to send a message to ThreadB ThreadA, first you have to prepare a Looper in ThreadA, which is great news poll butler then ready to send the message Handler, ready to send the message Handler is easy to understand, and that is to generate a Handler object in ThreadA, then prepare Looper how to do it? Called in ThreadA Looper.prepare (), then call Looper.loop () can be, so why call it? We do not see how such a code is called it in the main UI thread? In fact, they are called source inside, we have not seen, so in order to very familiar Handler mechanism, we need to study research Handler source code, so that we will know why so I write the code here to make ThreadB thread sends to ThreadA thread message so as to achieve sub-sub-thread thread Handler object asynchronous communication.

6.Android native package wheels based Handler

AsyncTask
HandlerThread
IntentService

7.Handler principle of resolution (from the bottom angle)

Be summed up

Interview questions (how to detect their own learning)

  • 1. The child must not update the UI thread it? (School & internships recruit)
  • Principle 2. Tell me about Handler's (school recruit & internship)
  • 3.Handler lead to memory leaks How do you solve?
  • 4. How to use Handler let the child thread and sub-thread communication?
  • 5. Can you give me about the design principles of Handler?
  • What is the principle 6.HandlerThread & & usage scenarios?
  • What 7.IdleHandler that?
  • 8. Can you create a thread correspondence between multiple Handler, Handler and Looper?
  • 9. Why Android system is not recommended to visit the child thread UI?
  • 10.Looper Why does not lead to an infinite loop applications stuck?
  • 11. Use postDealy Handler message queue any changes?
  • 12. Can a child thread Handler out of it in direct new?
  • What are the difference between the way 13.Message & objects created?
  • 14.ANR and Handler exist any link?
  • Looper Looper main thread and the child thread 15. What is the difference?
  • 16. Why can not talk about Handler Cross-process communication?
  • 17.Handler message delay is how to achieve?
  • 18. What is the message barrier?
  • 19. Suppose the new main thread and Handler A Handler B and Handler C, there are sub-thread, a message sent by the child thread Handler C, and then Handler A Handler B can receive it? why?

Note: The end of the article the author himself face questions from the summary, or want to find the answer exchange, start author GitHub project AndroidFaceInterview

Updated: 2020-01-15

Recommended: company LOGO design

Guess you like

Origin www.cnblogs.com/1994jinnan/p/12644204.html