User Tools

Site Tools


code:android-code:use-thread-in-ui

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Both sides previous revisionPrevious revision
Next revision
Previous revision
code:android-code:use-thread-in-ui [2010/04/12 13:34] percycode:android-code:use-thread-in-ui [2016/05/05 13:07] (current) – external edit 127.0.0.1
Line 1: Line 1:
 +====== 如何在Android 上层UI中调用Thread方法 ======
  
 +
 +虽然这种方法可以用,但还是不怎么推荐,如果涉及到[[WP>线程]]阻塞的问题,最好用AsyncTask来解决
 +
 +====== 方法一 ======
 +
 +<code java>
 +        new Thread(new Runnable() {
 +            public void run() {
 +                Looper.prepare();
 +                
 +                //do something here
 +                //postReport(statusCode, url);
 +
 +                Looper.loop();
 +            }
 +        }).start();
 +
 +</code>
 +
 +====== 方法二 ======
 +
 +<code java>
 +
 +class LooperThread extends Thread {
 +     public Handler mHandler;
 +       
 +     public void run() {
 +            Looper.prepare();
 +            
 +           mHandler = new Handler() {
 +               public void handleMessage(Message msg) {
 +                    // process incoming messages here
 +                }
 +         };
 +            
 +        Looper.loop();
 +</code>
 +
 +====== 出处 ======
 +
 +关键在下面两个函数,相关说明可以在Looper.java(android.os.Looper)里找到
 +  Looper.prepare();
 +  Looper.loop();
 +
 +
 +<code>
 +android.os.Looper
 +Class used to run a message loop for a thread. Threads by default do not have a message loop associated with them; to create one, call prepare in the thread that is to run the loop, and then loop to have it process messages until the loop is stopped. 
 +
 +Most interaction with a message loop is through the Handler class. 
 +
 +This is a typical example of the implementation of a Looper thread, using the separation of prepare and loop to create an initial Handler to communicate with the Looper. 
 +
 +  class LooperThread extends Thread {
 +      public Handler mHandler;
 +      
 +      public void run() {
 +          Looper.prepare();
 +          
 +          mHandler = new Handler() {
 +              public void handleMessage(Message msg) {
 +                  // process incoming messages here
 +              }
 +          };
 +          
 +          Looper.loop();
 +      }
 +  }
 +
 +</code>