Handler interview knowledge details, handler interview details
Preface
Today, let's review Handler. Considering performance optimization, the Android UI thread is thread insecure. To avoid UI display disorder caused by concurrent UI operations by multiple threads, Android allows you to modify and update the UI component only in the UI thread. Android is thrown when other threads update the UI. view. viewRootImpl $ CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views. exception. When we need to update the UI when the sub-thread completes time-consuming operations, we need to implement it through Handler.
1. What is Handler?
1. Handler sends and processes Message and Runnable objects to associate the MessageQueue of the corresponding thread.
2. Communication between threads.
2. Handler usage
Post (runnable)
SendMessage (message)
3. How Handler works
Handler: responsible for sending and processing messages. Logoff: Manages MessageQueue, extracts messages from MessageQueue, and submits them to the corresponding Handler for processing. A thread has only one logoff object. Message: the Handler receives and processes the Message object. MessageQueue: Message Queue, responsible for Message Management, first-in-first-out. When the program creates a logoff object, it will create a MessageQueue object in its constructor.
Summary:
1. First, logoff. prepare () saves a logoff instance in this thread, and then saves a MessageQueue object in this instance because of logoff. prepare () can be called only once in a thread, so MessageQueue only has one.
Initialize get. dispatchMessage (msg) method.
3. the Handler constructor will first obtain the logoff instance saved in the current thread and associate it with MessageQueue In The logoff instance.
4. The sendMessage method of Handler will assign the target value of msg to handler itself and add it to MessageQueue.
When constructing a handlerance construct in step 5, we will re-write handlemessagemessages, and parse the method finally called by msg.tar get. dispatchMessage (msg.
Android asynchronous Message processing mechanism allows you to deeply understand the relationship among logoff, Handler, and Message.
4. Memory leakage caused by Handler
Cause: the non-static internal class holds the anonymous reference of the external class, and the Activity cannot be released.
Solution:
Handler internally holds weak references to external activities. Change Handler to static internal class. Handler. removeCallback (). 5. Code practices
There are 1st Handler types created in the UI thread. The subthread sends messages and the UI thread receives the messages for processing:
Logoff is called in the current UI thread in the Activity startup code. prepare () and logoff. loop () method, so we can create Handler in the Activity. For details, we can view the main method of the ActivityThread class, and we will find that logoff is called. preparemainlogoff () and logoff. loop () method.
ActivityThread:
Public final class ActivityThread {public static void main (String [] args) {// some code is omitted // The prepareMainLooper () method calls Looper. prepare (false); creates a logoff object. prepareMainLooper (); // start polling Looper. loop (); // the following code finds that in the UI thread, we cannot manually call and stop the Loop, otherwise an exception will be thrown. Throw new RuntimeException ("Main thread loop unexpectedly exited ");}}
Example: The specific code of Toast is displayed in the UI thread when the subthread sends a message:
Package com. example. ling. review. handler; import android. OS. bundle; import android. OS. handler; import android. OS. message; import android. support. v7.app. appCompatActivity; import android. widget. toast; import com. example. ling. review. r; import java. lang. ref. weakReference; public class HandlerActivity extends AppCompatActivity {private Handler mHandler = new MainHandler (this); // change Handler to static internal class to avoid Memory leakage public static class MainHandler extends Handler {private WeakReference
MWeakReference = null; public MainHandler (HandlerActivity activity) {// encapsulate the Activity as a weak reference to avoid Memory leakage mWeakReference = new WeakReference <> (activity );} @ Override public void handleMessage (Message msg) {// receives and processes the Message. HandlerActivity = mWeakReference. get (); if (activity! = Null) {Toast. makeText (activity, "I am on the UI thread", Toast. LENGTH_SHORT ). show () ;}}@ Override protected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_handler); initView ();} private void initView () {new Thread (new Runnable () {@ Override public void run () {try {Thread. sleep (2000); // first post (runnable) usage mHandler. post (new Runnable (){ @ Override public void run () {Toast. makeText (getApplicationContext (), "I am on the UI thread", Toast. LENGTH_SHORT ). show () ;}}); // The second sendMessage (message) usage Thread. sleep (2000); Message message = Message. obtain (); mHandler. sendMessage (message);} catch (InterruptedException e) {e. printStackTrace ();}}}). start () ;}@ Override protected void onDestroy () {super. onDestroy (); // Handler removes all reconciliation information when the activity is destroyed. If (mHandler! = Null) {mHandler. removeCallbacksAndMessages (null); mHandler = null ;}}}
2nd the seed thread creates a Handler, sends messages to the subthread, and creates a Handler thread to receive messages for processing:
1. The sub-thread needs to create the logoff object by itself when using Handler. 2. After creating the logoff object, the Handler object is created. 3. Enable logoff polling, and the Handler can send and process messages;
Example:
Public class HandlerActivity2 extends AppCompatActivity {private ThreadHandler mHandler; // change Handler to a static internal class to avoid Memory leakage public static class ThreadHandler extends Handler {@ Override public void handleMessage (Message msg) {// receives and processes the message Log. d ("TAG", "Receive message ----- the current Thread is:" + Thread. currentThread (). getName () ;}@ Override protected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState ); SetContentView (R. layout. activity_handler); newThread1 (); newThread2 ();}/*** create sub-Thread 1 create Handler */private void newThread1 () {new Thread (new Runnable () {@ Override public void run () {Log. d ("TAG", "current Thread:" + Thread. currentThread (). getName (); // 1. Create a logoff. prepare (); // 2. Create Handler mHandler = new ThreadHandler (); // 3. Start logoff. loop ();}}). start ();}/*** create sub-thread 2 and use the handler of sub-thread 1 to send and remove Information */private void newThread2 () {new Thread (new Runnable () {@ Override public void run () {try {Log. d ("TAG", "current Thread:" + Thread. currentThread (). getName (); Thread. sleep (2000); Message message = Message. obtain (); mHandler. sendMessage (message);} catch (InterruptedException e) {e. printStackTrace ();}}}). start () ;}@ Override protected void onDestroy () {super. onDestroy (); // Handler moves when activity is destroyed Except all reconciliation information, if (mHandler! = Null) {mHandler. removeCallbacksAndMessages (null); mHandler = null ;}}}
The running result is as follows:
We found that the Handler was created in the Thread-2 subthread, sent messages in the Thread-3 subthread, and received messages in the Thread-2 subthread.