Under the Android platform, when multithreaded programming, it is often necessary to do some processing in a separate thread outside the main threads, and then update the user interface display. However, the problem with directly updating the page in a thread other than the main thread is that the system will report this exception, android.view.viewroot$calledfromwrongthreadexception:only the original thread That's created a view hierarchy can touch their views. (Only the thread that originally created this view hierachy can modify its view.) )。
That is, you must perform the work of updating the interface in the main thread of the program (that is, the UI thread). You can use one of the following methods to resolve:
Solution 1: Create an instance of the handler class in Activity.oncreate (Bundle savedinstancestate) and invoke the function shown in the update interface in the handler callback function of this handlemessage instance. For example:
public class Exampleactivity extends activity {
Handler h = null;
@override public
void OnCreate (Bundle savedinstancestate) {
h = new Handler () {
@override public
Void Handlemessage (msg) {
//Call Update GUI method.}
}
;
}
In other functions, send or post a message to this h using the Send family or the post family function.
Solution 2: Using Activity.runonuithread (runnable)
Create the updated UI code in runnable, and then pass the Runnable object to Activity.runonuithread (Runnable) When the UI needs to be updated. This allows runnable to be invoked in the UI program.