On a brief introduction about Looper's simple knowledge, this article we introduce the multithreading of concurrent processing, we know that handler through SendMessage () sent the message, first sent to the looper, deposited looper message stack, The handler object processes the message through the Handmessage () method after it is newly sent to the handler object. Here it is easy to see a null pointer exception, let's look at this code together:
Public classMainactivityextendsActivity {classMythreadextendsthread{PrivateHandler Handler; PrivateLooper Looper; @Override Public voidrun () {looper.prepare ();//Create a Looper objectLooper =Looper.mylooper (); Handler=NewHandler () {@Override Public voidhandlemessage (Message msg) {System.out.println ("Child Thread:" +Thread.CurrentThread ()); } }; Looper.loop ();//This method of cyclic processing } }; PrivateMythread thread; PrivateHandler SecondHandler; @Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate); Setcontentview (R.layout.activity_main); Thread=NewMythread (); Thread.Start (); Try{Thread.Sleep (3000); } Catch(interruptedexception e) {e.printstacktrace (); } thread.handler.sendEmptyMessage (1);//processing in a child threadSecondHandler=NewHandler (thread.looper) {@Override Public voidhandlemessage (Message msg) {System.out.println (msg); } }; Secondhandler.sendemptymessage (1); }}
This is a null pointer exception, because when our secondhandler is created, this exception occurs if the Thread.looper object has not yet been created. So how to prevent this anomaly? Google has taken this into account when designing Android, and here we will use Handlerthread to deal with this problem of multithreading concurrency.
/*** NULL pointer problem when processing multithreading concurrency with Handlerthread*/ Public classSecondactivityextendsActivity {PrivateHandlerthread Handlerthread; PrivateHandler Handler; PrivateTextView text; @Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate); //Create a TextViewText =NewTextView ( This); Text.settext ("Helloword"); Setcontentview (text); //to create a handler thread objectHandlerthread =NewHandlerthread ("Handler thread");//a name for the current threadHandlerthread.start ();//Start ThreadHandler =NewHandler (Handlerthread.getlooper ()) {@Override Public voidhandlemessage (Message msg) {System.out.println ("Current:" +Thread.CurrentThread ()); } }; Handler.sendemptymessage (1); } }
Android thread concurrency processing