Update the interface in the child thread of the android development tutorial

  • 2020-05-24 06:10:47
  • OfStack

Each Handler object is associated with the thread that created it, and each Handler object can only be associated with one thread.
Handler1 can be used in two ways: 1) to perform scheduled tasks, which you can preorder to perform certain tasks, and to simulate the timer. 2) communication between threads. When the Android application starts, a main thread is created, which creates a message queue to process the various messages. When you create a child thread, you can take the Handler object created in the parent thread from your child thread and send a message to the parent thread's message queue through this object. Since Android requires the interface to be updated in an UI thread, you can update the interface in other threads using this method.

Example of updating an interface in a child thread via Runnable

Create Handler in onCreate


public class HandlerTestApp extends Activity { 
Handler mHandler; 
TextView mText; 
/** Called when the activity is first created. */ 
   @Override 
   public void onCreate(Bundle savedInstanceState) { 
   super.onCreate(savedInstanceState); 
   setContentView(R.layout.main); 
   mHandler = new Handler();// create Handler 
   mText = (TextView) findViewById(R.id.text0);//1 a TextView 
   }

Build the Runnable object and update the interface in runnable, where we have modified the TextView text. Note here that the Runnable object can be created in the main thread or in the child thread. We created it here in a child thread.

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

Create a child thread, in the run function of the thread, we send an runnable to the message queue of the main thread to update the interface.


privatevoidupdateUIByRunnable(){
newThread()
{
//Messagemsg=mHandler.obtainMessage();
publicvoidrun()
{
//mText.setText("ThisisUpdatefromohterthread,MouseDOWN");// This sentence will throw an exception 
mHandler.post(mRunnable0);
}
}.start();
}

Update the interface in a child thread with Message
Updating the Message interface is similar to updating the Runnable interface, except that it requires a few changes.
Implement your own Handler to process messages


privateclassMyHandlerextendsHandler
{
@Override
publicvoidhandleMessage(Messagemsg){
//TODOAuto-generatedmethodstub
super.handleMessage(msg);
switch(msg.what)
{
caseUPDATE:// The interface is updated when a message is received 
mText.setText("Thisupdatebymessage");
break;
}
}
}

Send a message in the new thread


privatevoidupdateByMessage()
{
// Anonymous objects 
newThread()
{
publicvoidrun()
{
//mText.setText("ThisisUpdatefromohterthread,MouseDOWN");
//UPDATE is 1 A self - defined integer that represents the message ID
Messagemsg=mHandler.obtainMessage(UPDATE);
mHandler.sendMessage(msg);
}
}.start();
}


Related articles: