`
panxq0809
  • 浏览: 294789 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

message loop for an thread

阅读更多

message loop for an thread

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();
     
}
 
}
------------------------------------------------------------------------------------------
public class Looper {

    // sThreadLocal.get() will return null unless you've called prepare().
    private static final ThreadLocal sThreadLocal = new ThreadLocal();

    final MessageQueue mQueue;

    /** Initialize the current thread as a looper.
     * This gives you a chance to create handlers that then reference
     * this looper, before actually starting the loop. Be sure to call
     * {@link #loop()} after calling this method, and end it by calling
     * {@link #quit()}.
     */
    public static final void prepare() {
        if (sThreadLocal.get() != null) {
            throw new RuntimeException("Only one Looper may be created per thread");
        }
        sThreadLocal.set(new Looper());
    }
    private Looper() {
        mQueue = new MessageQueue();
        mRun = true;
        mThread = Thread.currentThread();
    }
    public static final void loop() {
        Looper me = myLooper();
        MessageQueue queue = me.mQueue;
        while (true) {
            Message msg = queue.next(); // might block
            //if (!me.mRun) {
            //    break;
            //}
            if (msg != null) {
                if (msg.target == null) {
                    // No target is a magic identifier for the quit message.
                    return;
                }
                if (me.mLogging!= null) me.mLogging.println(
                        ">>>>> Dispatching to " + msg.target + " "
                        + msg.callback + ": " + msg.what
                        );
                msg.target.dispatchMessage(msg);      //msg.target鏄痗lass Handler绫诲瀷
                if (me.mLogging!= null) me.mLogging.println(
                        "<<<<< Finished to    " + msg.target + " "
                        + msg.callback);
                msg.recycle();
            }
        }
    }
    /**
     * Return the Looper object associated with the current thread.  Returns
     * null if the calling thread is not associated with a Looper.
     */
    public static final Looper myLooper() {
        return (Looper)sThreadLocal.get();
    }

    ......
}



public class Handler {
    ...
    public Handler() {
        ...
        if (FIND_POTENTIAL_LEAKS) {
            final Class<? extends Handler> klass = getClass();
            if ((klass.isAnonymousClass() || klass.isMemberClass() || klass.isLocalClass()) &&
                    (klass.getModifiers() & Modifier.STATIC) == 0) {
                Log.w(TAG, "The following Handler class should be static or leaks might occur: " +
                    klass.getCanonicalName());
            }
        }

        mLooper = Looper.myLooper();
        if (mLooper == null) {
            throw new RuntimeException(
                "Can't create handler inside thread that has not called Looper.prepare()");
        }
        mQueue = mLooper.mQueue;
        mCallback = null;
    }

    public interface Callback {
        public boolean handleMessage(Message msg);
    }

    public void handleMessage(Message msg) {
    }
   
    public void dispatchMessage(Message msg) {
        if (msg.callback != null) {
            handleCallback(msg);
        } else {
            if (mCallback != null) {
                if (mCallback.handleMessage(msg)) {
                    return;
                }
            }
            handleMessage(msg);
        }
    }

    final MessageQueue mQueue;
    final Looper mLooper;
    final Callback mCallback;

}

 

 

分享到:
评论

相关推荐

    opc 客户端程序 可以连接OPC服务器

    The FSServer DLL creates a thread that runs its own message loop and registers its COM objects for free-threaded use. It handles all OPC communications. It just relies on the application to provide ...

    BURNINTEST--硬件检测工具

    - A parallel port loop back plug for the parallel port test. - A USB port loop back plug for the USB port test. - A USB 2.0 port loop back plug for the USB 2.0 port test. - PassMark ModemTest V1.3 ...

    acpi控制笔记本风扇转速

    the Switch() operator is within a while loop, causing an error on the second iteration. (BZ 460) Disassembler - fix for error emitted for unknown type for target of scope operator. Now, ignore it and...

    一个win32下的ARM开源编译器

    This package is an ARM assembler add-on for FASM. FASMARM currently supports the full range of instructions for 32-bit and 64-bit ARM processors and coprocessors up to and including v8. Contents: ...

    Sakemail

    does not format the message in multipart mode if people send an attach, without writing any text and with no MIME settings. Fixed. This could be serious, I recommend upgrading.1.8.8- A small fix with ...

    delphi编译错误.txt

    FOR-Loop variable ''''&lt;Name&gt;'''' may be undefined after loop 在循环后的FOR循环变量是不确定的 Function needs result type 函数需要结果类型 Identifier redeclared: ''''&lt;name&gt;'''' 标识符重复说明 Illegal ...

    微软内部资料-SQL性能优化3

    An isolation level determines the degree to which data is isolated for use by one process and guarded against interference from other processes. Prior to SQL Server 7.0, REPEATABLE READ and ...

    python3.6.5参考手册 chm

    PEP 372: Adding an Ordered Dictionary to collections PEP 378: Format Specifier for Thousands Separator PEP 389: The argparse Module for Parsing Command Lines PEP 391: Dictionary-Based Configuration...

    stdafx.h代码

    // Type modifier for message handlers #ifndef afx_msg #define afx_msg // intentional placeholder #endif #undef AFX_DATA #define AFX_DATA AFX_CORE_DATA /////////////////////////////////////////////...

    SimIt-ARM-3.0 ARM指令模拟器

    SimIt-ARM-3.0 给予命令行ARM指令模拟器,短小精悍,是研究ARM处理器的好工具,该模拟器既可以运行用户级别的ELF程序,又可以模拟运行Linux操作系统...Calibrating delay loop... 367.82 BogoMIPS Memory: 32MB = 32MB...

    手机游戏开发实例(smartphone联机炸弹人)

    Windows Programming and Message Handling essentials ...........................................................................8 II.1.3. Drawing Bitmaps to the screen.................................

    Tricks of the Windows video Game Programming---part1

    ..........................................................59 Dissecting the Program....................................................................60 Choosing a Message Box ....................

Global site tag (gtag.js) - Google Analytics