当前位置:文档之家› 【嵌入式】android基础教程Looper和Handler

【嵌入式】android基础教程Looper和Handler

android基础教程Looper和Handler

Looper用于在Android线程中进行消息处理,默认情况下,一个线程并不和任何Looper绑定。当我们调用Looper.prepare()时,如果当前线程还没有和任何Looper绑定,那么将创建一个Looper让它和当前线程绑定。当我们调用Looper.loop()时,它将对当前线程所对应的Looper的消息进行处理,从消息队列里取消息,处理消息,一直循环直到对该Looper 调用quit()函数。

注意:Looper.loop()中是个while循环,只有对它所在线程的Looper调用了quit()函数,Looper.loop()函数才能完成,其后的代码才能得以运行。一个线程对应一个Looper,一个Looper对应一个消息队列MessageQueue。

对于Handler,其实只是把消息发送到其对应的Looper的消息队列MessageQueue中,最后的处理还是在Looper.loop()的while循环中进行的。一个Looper可以用于构造多个Handler。因为Looper.loop()函数是个while循环,会让当前线程一直在那里处理进行循环,直到对该线程的Looper调用了quit()函数,所以,如果想对该Handler发送消息或添加Runnable以进行事务处理,要么在别的线程中进行,要么在该Handler在处理消息时或在Runnable()的run()函数中进行事务处理时进行。

注意:Handler的构造函数Handler()和Handler(Handler.Callback callback),虽然没有Looper参数,但是它实际上是通过Looper.myLooper()来获取当前线程中的Looper的。

以下是Android API中的一个典型的Looper thread实现

示例1:

Java代码: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的,所以要调用 Looper.prepare()来给线程创建消息循环,然后再通过,Looper.loop()来使消息循环起作用。

另外,Activity的MainUI线程已经新建并绑定了个Looper(在源码1的,Main函数中你可以看到)。所以在Activity中新建Handler时,不需要先调用Looper.prepare()。

关于Activity的MainUI线程的更多内容可以查看源码文件ActivityThread.java,它位于android\frameworks\base\core\java\android\app下

源码1

java代码:

public final class ActivityThread {

//省略

final ApplicationThread mAppThread = new ApplicationThread();

final Looper mLooper = Looper.myLooper();

final H mH = new H();

//省略

private final class H extends Handler {

//省略

}

//省略

public static final void main(String[] args) { SamplingProfilerIntegration.start();

Process.setArgV0("");

Looper.prepareMainLooper();

if (sMainThreadHandler == null) {

sMainThreadHandler = new Handler();

}

ActivityThread thread = new ActivityThread();

thread.attach(false);

if (false) {

Looper.myLooper().setMessageLogging(new

LogPrinter(Log.DEBUG, "ActivityThread"));

}

Looper.loop();

if (Process.supportsProcesses()) {

throw new RuntimeException("Main thread loop unexpectedly exited"); }

thread.detach();

String name = (thread.mInitialApplication != null)

? thread.mInitialApplication.getPackageName()

: "";

Slog.i(TAG, "Main thread of " + name + " is now exiting");

}

嵌入式相关资料,欢迎下载!

相关主题
文本预览
相关文档 最新文档