dim*_*suz 5 user-interface multithreading android
我有一个带有两个线程的应用程序-主线程和数据加载器。数据加载器完成后,它将Runnable对象发布到主线程中(如DevGuide中所述),但它从未交付并运行。
这是基本代码:
class MyApp extends Application
{
public void onCreate()
{
LoaderThread t = new LoaderThread();
t.start();
}
private class LoaderThread extends Thread
{
public void run()
{
SystemClock.sleep(2000);
boolean res = m_handler.post(m_runnable);
if(res)
Log.d(TAG, "Posted Runnable");
}
}
private final Handler m_handler = new Handler();
private final Runnable m_runnable = new Runnable() {
public void run()
{
Log.d(TAG, "Hey, i'm runnable!");
}
}
}
Run Code Online (Sandbox Code Playgroud)
同样可能需要注意的是,我将此代码作为从ApplicationTestCase派生的单元测试来运行:
class MyAppTest : public ApplicationTestCase
{
public MyAppTest()
{
super(MyApp.class);
}
public void testLoading()
{
createApplication();
// few asserts follow here...
}
}
Run Code Online (Sandbox Code Playgroud)
所以这失败了。尽管日志表明已成功发布了Runnable,但从未调用过run()。我还尝试发送简单消息,而不是发布可运行消息(例如m_handler.sendEmptyMessage(1))-它们从未传递到主线程中的处理程序回调中。
我在这里想念什么?
提前致谢 :)
AHandler需要 aLooper才能工作。提供Looper了 所需的消息队列Handler。
所有 的实例Activity都有一个Looper用于处理 UI 事件,但您可以Looper在其他地方创建您的实例。
查看您的日志输出,看看 Android 是否抱怨缺少Looper.
如果是这样,您可以通过将以下内容添加到onCreate()方法的顶部来修复:
Looper.prepare();
m_handler = new Handler();
Looper.run();
Run Code Online (Sandbox Code Playgroud)
m_handler并从代码中稍后删除初始化。