1 PackageCom.example.gp08_day26_handler3;2 3 ImportAndroid.os.Bundle;4 ImportAndroid.os.Handler;5 ImportAndroid.os.Looper;6 ImportAndroid.os.Message;7 Importandroid.app.Activity;8 ImportAndroid.view.Menu;9 ImportAndroid.view.View;Ten One /** A * The main thread sends messages to child threads - * @authorQQ - * the */ - Public classMainactivityextendsActivity { - - PrivateHandler Handler;//you need to instantiate in a child thread + @Override - protected voidonCreate (Bundle savedinstancestate) { + Super. OnCreate (savedinstancestate); A Setcontentview (r.layout.activity_main); at } - - Public voidSendMessage (View v) - { - //Click the button to send a message to the child thread -Message msg =Message.obtain (); inMsg.obj = "Hello, hi!"; - //The message object is put into the MessageQueue object inside the handler, and the MessageQueue reference inside the handler points to Looper in MessageQueue to handler.sendmessage (msg); + } - //Creating child Threads the classMyThreadextendsThread * { $ Public voidRun ()Panax Notoginseng { - //need to have Looper object first theLooper.prepare ();//creates a Looper object and puts the object into the local variable of the thread, creating the MessageQueue object in the Looper constructor method + //instantiating handler in a child thread, no Looper object in the child thread A the //mqueue = mlooper.mqueue; MessageQueue references inside Handler point to Looper objects in MessageQueue +Handler =NewHandler ();//if handler is instantiated directly, the exception is new runtimeexception because there are no Looper objects in the child thread - $ //let the Looper object iterate through the messages in the MessageQueue $ //The loop reads the message from the queue and, when it reads the message, goes back to call Msg.target.dispatchMessage (msg); - //There is a target member in the message class, and when the message is sent, the target member is assigned the current handler object - Looper.loop (); the } - }Wuyi the}mainactivity
Handler communication mechanism