code:android-code:use-thread-in-ui
Differences
This shows you the differences between two versions of the page.
| Both sides previous revisionPrevious revisionNext revision | Previous revision | ||
| code:android-code:use-thread-in-ui [2010/04/12 13:34] – percy | code: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方法 ====== | ||
| + | |||
| + | 虽然这种方法可以用, | ||
| + | |||
| + | ====== 方法一 ====== | ||
| + | |||
| + | <code java> | ||
| + | new Thread(new Runnable() { | ||
| + | public void run() { | ||
| + | Looper.prepare(); | ||
| + | | ||
| + | //do something here | ||
| + | // | ||
| + | |||
| + | Looper.loop(); | ||
| + | } | ||
| + | }).start(); | ||
| + | |||
| + | </ | ||
| + | |||
| + | ====== 方法二 ====== | ||
| + | |||
| + | <code java> | ||
| + | |||
| + | class LooperThread extends Thread { | ||
| + | | ||
| + | |||
| + | | ||
| + | Looper.prepare(); | ||
| + | | ||
| + | | ||
| + | | ||
| + | // process incoming messages here | ||
| + | } | ||
| + | }; | ||
| + | | ||
| + | Looper.loop(); | ||
| + | </ | ||
| + | |||
| + | ====== 出处 ====== | ||
| + | |||
| + | 关键在下面两个函数, | ||
| + | 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(); | ||
| + | } | ||
| + | } | ||
| + | |||
| + | </ | ||
