`
panxq0809
  • 浏览: 296816 次
  • 性别: 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;

}

 

 

分享到:
评论

相关推荐

    C & C++ Win32 API Programming

    - **Message Queue**: Windows maintains a message queue for each thread. Messages are placed in the queue and retrieved by the message loop. - **Message Loop**: The message loop retrieves messages from...

    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 ...

    android 线程间通信

    Log.i(TAG, "Got an incoming message from the child thread: " + (String)msg.obj); info.setText((String)msg.obj); } }; ``` #### 四、示例:简单的线程间通信 以下是一个简单的线程间通信示例,展示如何在...

    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 ...

    微软内部资料-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 /////////////////////////////////////////////...

    delphi编译错误.txt

    11. **Assignment to FOR-Loop variable `&lt;Name&gt;`** - **含义**: 不允许直接给 FOR 循环变量 `&lt;Name&gt;` 赋值。 - **解决办法**: 移除对循环变量的赋值操作。 12. **Bad argument type in variable type array ...

    SimIt-ARM-3.0 ARM指令模拟器

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

    Ruby程序设计(简洁清新的教程)

    puts "Caught an exception: #{e.message}" end ``` **9.2 定义异常类** 可以自定义异常类: ```ruby class MyException end raise MyException.new("Custom error message.") ``` **9.3 catch和throw** `...

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

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

    ruby初学者教程(对初学者很有帮助)

    Ruby提供了多种循环结构,如`loop`、`while`、`until`等。 ```ruby i = 0 while i puts i i += 1 end ``` #### 七、方法 **7.1 运算符重定义** 可以通过定义特定的方法名来重定义运算符的行为。 ```ruby ...

    Tricks of the Windows video Game Programming---part1

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

Global site tag (gtag.js) - Google Analytics