User Tools

Site Tools


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

如何在Android 上层UI中调用Thread方法

虽然这种方法可以用,但还是不怎么推荐,如果涉及到线程阻塞的问题,最好用AsyncTask来解决

方法一

        new Thread(new Runnable() {
            public void run() {
                Looper.prepare();
 
                //do something here
                //postReport(statusCode, url);
 
                Looper.loop();
            }
        }).start();

方法二

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();

出处

关键在下面两个函数,相关说明可以在Looper.java(android.os.Looper)里找到

Looper.prepare();
Looper.loop();

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();
      }
  }

/var/www/dokuwiki/wiki/data/pages/code/android-code/use-thread-in-ui.txt · Last modified: 2016/05/05 13:07 by 127.0.0.1