Handler Looper的简单例子

View Code 
public class LooperTest extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        new Thread(new PrintLog()).start();
    }
public class PrintLog implements Runnable{
    private static int START_MESSAGE = 100;    
    private static int PRINT_MESSAGE = 101;    
    private static int INNER_MESSAGE = 102;    
    private static int SYNC_LATER_INTERVAL = 3 * 1000;
    private static int count = 0;
    
    private PrintHandler  mHandler;

    public class PrintHandler extends Handler{
        public void handleMessage(Message msg) {
            if (msg.what == START_MESSAGE) {
                count++;
                Log.d("PrintLog","START_MESSAGE:count :" + String.valueOf(count));     
                
                Message newmsg = obtainMessage(PRINT_MESSAGE);
                sendMessageDelayed(newmsg, SYNC_LATER_INTERVAL);
            }
            
            if (msg.what == PRINT_MESSAGE) {
                count++;
                Message newmsg = obtainMessage(START_MESSAGE);
                sendMessageDelayed(newmsg, SYNC_LATER_INTERVAL);
                Log.d("PrintLog","print_message:count :" + String.valueOf(count));                            
            }
        }
    };    

    @Override
    public void run() {
        Log.d("PrintLog","run() start ");
        // TODO Auto-generated method stub
        Looper.prepare();
        mHandler = new PrintHandler();
        Message msg = mHandler.obtainMessage(START_MESSAGE);
        mHandler.sendMessageDelayed(msg, SYNC_LATER_INTERVAL);
        //mHandler.sendMessage(msg);
        Looper.loop();    
        Log.d("PrintLog","run() end");
    }

}

 (1) Looper类别用来为一个线程开启一个消息循环。默认情况下Android中新诞生的线程是没有开启消息循环的。(主线程除外,主线程系统会自动为其创建Looper对象,开启消息循环)

Looper对象通过MessageQueue来存放消息和事件。一个线程只能有一个Looper,对应一个MessageQueue。 

(2) 通常是通过Handler对象来与Looper交互的。Handler可看做是Looper的一个接口,用来向指定的Looper发送消息及定义处理方法。

默认情况下Handler会与其被定义时所在线程的Looper绑定,比如,在主线程中定义,其是与主线程的Looper绑定。

mainHandler = new Handler() 等价于new Handler(Looper.myLooper()).

Looper.myLooper():Return the Looper object associated with the current thread 获取当前进程的looper对象。

还有一个类似的 Looper.getMainLooper() 用于获取主线程的Looper对象。 

(3) 在非主线程中直接new Handler() 会报如下的错误:

E/AndroidRuntime( 6173): Uncaught handler: thread Thread-8 exiting due to uncaught exception
E/AndroidRuntime( 6173): java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()

原因是非主线程中默认没有创建Looper对象,需要先调用Looper.prepare()启用Looper。 

(4) Looper.loop(); 让Looper开始工作,从消息队列里取消息,处理消息。

注意:写在Looper.loop()之后的代码不会被执行,这个函数内部应该是一个循环,当调用mHandler.getLooper().quit()后,loop才会中止,其后的代码才能得以运行。 

Android Looper和Handler分析http://blog.csdn.net/Innost/article/details/6055793

原文地址:https://www.cnblogs.com/fangxiang/p/2371240.html