SoFunction
Updated on 2025-03-11

Android development tutorial update interface in child thread

Each Handler object is associated with the thread that created it, and each Handler object can only be associated with one thread.
Handlers generally have two uses: 1) Execute planned tasks. You can then perform certain tasks in a scheduled manner, and you can simulate a timer. 2) Inter-thread communication. When Android's application starts, a main thread will be created, and the main thread will create a message queue to process various messages. When you create a child thread, you can get the Handler object created in the parent thread from your child thread, and you can send messages to the parent thread's message queue through the object. Since Android requires the interface to be updated in UI threads, the interface can be updated in other threads through this method.

Example of updating interface in child threads via Runnable

Create Handler in onCreate

Copy the codeThe code is as follows:

public class HandlerTestApp extends Activity {
Handler mHandler;
TextView mText;
/** Called when the activity is first created. */
   @Override
   public void onCreate(Bundle savedInstanceState) {
   (savedInstanceState);
   setContentView();
mHandler = new Handler();//Create Handler
mText = (TextView) findViewById(.text0);//A TextView
   }

Build a Runnable object and update the interface in runnable. Here, we have modified the text of the TextView. It should be noted here that the Runnable object can be created in the main thread or in the child thread. We are created here in the child thread.
Copy the codeThe code is as follows:

RunnablemRunnable0=newRunnable()
{
@Override
publicvoidrun(){
//TODOAuto-generatedmethodstub
("ThisisUpdatefromohterthread,MouseDOWN");
}
};

Create a child thread. In the thread's run function, we send a runnable to the message queue of the main thread to update the interface.

Copy the codeThe code is as follows:

privatevoidupdateUIByRunnable(){
newThread()
{
//Messagemsg=();
publicvoidrun()
{
//("ThisUpdatefromhterthread,MouseDOWN");//This sentence will throw an exception
(mRunnable0);
}
}.start();
}

Use Message to update the interface in the child thread
The Message update interface is similar to the Runnable update interface, but it needs to be modified several places.
Implement your own Handler and process messages

Copy the codeThe code is as follows:

privateclassMyHandlerextendsHandler
{
@Override
publicvoidhandleMessage(Messagemsg){
//TODOAuto-generatedmethodstub
(msg);
switch()
{
caseUPDATE://update the interface when receiving the message
("Thisupdatebymessage");
break;
}
}
}

Send a message in a new thread

Copy the codeThe code is as follows:

privatevoidupdateByMessage()
{
//Anonymous object
newThread()
{
publicvoidrun()
{
//("ThisisUpdatefromohterthread,MouseDOWN");
//UPDATE is an integer defined by itself, representing the message ID
Messagemsg=(UPDATE);
(msg);
}
}.start();
}