Android implements the method of updating UI in Activity in sub threads

  • 2021-07-09 09:22:29
  • OfStack

This article illustrates how Android updates UI in Activity in sub-threads. Share it for your reference, as follows:

On the Android platform, when multithreaded programming, it is often necessary to do some processing in a separate thread outside the main thread, and then update the user interface display. However, the problem with updating the page display directly in a thread other than the main thread is that the system will report this exception:

ERROR/AndroidRuntime(1222): android.view.ViewRoot$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.

Perhaps a programmer will call the Toast. makeText () method in a thread and try to display some prompt information in UI, which will also report the following error:

Can't create handler inside thread that has not called Looper.prepare()

Solution: Sub-threads can not directly update UI in Activity. The general practice is that sub-threads pass messages to Activity, and then Activity updates UI according to these messages. There is a class in Android called android. os. Handler, which is used to do this.

1. Declare a variable of class android. os. Handler in Activity that needs to be updated by the thread,


private Handler handler;

2. The initialization of handler is added to the onCreate function:


@Override
public void onCreate(Bundle savedInstanceState) {
// Other codes … 
// ... 
// ... 
handler=new Handler(){
public void handleMessage(Message msg){
String message=(String)msg.obj;//obj No 1 It must be String Class, can be other classes, see the specific application of users 
 // According to message The information in the main thread's UI Make changes 
 // ...                            }
}
};

In addition, Activity needs to provide get function of handler, so that threads can get handler and pass messages.


public Handler getHandler(){
return this.handler;
}

3. The sub-thread class needs to hold the Context class object representing the context. In practical application, this reference points to the Activity object to update UI, which is generally declared as:


private Context ctx;

Then initialize ctx in the child thread class constructor or other function. This step is to get the Handler object in the Activity object. (Or otherwise, as long as the child thread can get the handler object in Activity.)

4. In the last step, when the sub-thread runs somewhere and needs to deliver messages to Activity, create an object of android. os. Message class, add the object to be transmitted to message, and publish it to the main thread through Handler. The code example is as follows:


String str_temp=" Message to be passed to the main thread "
Message message = Message.obtain();
message.obj=str_temp;
// Pass Handler Publish and send messages, handler
handler.sendMessage(message);

Remember, handler here is the same object as handler in Activity, so that the message is sent to that Activity.

In addition, this method not only allows child threads to update UI, but also can be used for other purposes. Now let's assume that a child thread might throw some errors, which should be normal, so how can the error message be made known to users? Very simple, in the catch statement block, put the error object to catch into message. obj, pass it to Activity, and use Toast. makeText () method to display the error message in Activity.

More readers interested in Android can check the topic of this site: "Android Thread and Message Mechanism Usage Summary", "activity Operation Skills Summary of Android Programming", "Android Debugging Skills and Common Problem Solutions Summary", "Android Development Introduction and Advanced Tutorial", "Android Multimedia Operation Skills Summary (Audio, Video, Recording, etc.)", "Android Basic Component Usage Summary", "Android View View Skill Summary", "Android Layout layout Skill Summary" and "Android Control Usage Summary"

I hope this article is helpful to everyone's Android programming.


Related articles: