使用自己页面的looper,
HandlerThread thread = new HandlerThread("DockService");
thread.start();
mServiceLooper = thread.getLooper();
mServiceHandler = new ServiceHandler(mServiceLooper);
@Override
public void onDestroy() {
if (DEBUG) Log.d(TAG, "onDestroy");
mServiceLooper.quit();
}
<pre class="java" name="code">如果需要在子线程中使用Handler类,首先需要创建Looper类实例,这时可以通过Looper.prepare()和Looper.loop()函数来实现的。阅读Framework层源码发现,<a target=_blank class="UBBWordLink" href="http://tech.cncms.com/shouji/android/" target="_blank">Android</a>为我们提供了一个HandlerThread类,该类继承Thread类,并使用上面两个函数创建Looper对象,而且使用wait/notifyAll解决了多线程中子线程1获取子线程2的Looper对象为空的问题。