Under the Android platform, for 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 directly updating the page display 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 created a view hierarchy can touch it views. (Only the thread that originally created the view hierachy) can modify its view. )。
This means that the interface must be updated 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 Handlemessage callback function of the handler instance. For example:
[Java]View Plaincopy
- Public class Exampleactivity extends Activity {
- Handler h = null;
- @override
- public void OnCreate (Bundle savedinstancestate) {
- h = New Handler () {
- @override
- public void Handlemessage (Message msg) {
- //Call Update GUI method.
- }
- };
- }
- }
In other functions, send or mail messages to this h using the Send family or post family functions.
Solution 2: Leverage Activity.runonuithread (runnable)
The code that updates the UI is created in Runnable, and the Runnable object is passed to Activity.runonuithread (runnable) When the UI needs to be updated. This way, the runnable can be called in the UI program.
Note that the runnable in this place is not actually a dynamic update, and if you use this method in OnCreate, the interface will not show up, as it is necessary to wait for the Runnable method call to complete before the display interface can be displayed. So by initializing the interface to get the network data, it is not advisable to use this method directly ...
As follows:
[Java]View Plaincopy
- Class Test implements Runnable
- {
- @Override
- public Void Run ()
- {
- int len = 3;
- int i=0;
- While (i < len)
- {
- System.out.println ("LJZ");
- i++;
- Textview.settext ("Hello |" + System.currenttimemillis ());
- Textview.invalidate ();
- try {
- Thread.Sleep (1000);
- } catch (Exception e) {
- E.printstacktrace ();
- }
- }
- }
- }
Make the following call in the main interface:
MainActivity.this.runOnUiThread (test);
The result is that the method of creating the OnCreate time is getting bigger.