首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >检查是否需要RunOnUiThread?

检查是否需要RunOnUiThread?
EN

Stack Overflow用户
提问于 2011-08-15 20:07:54
回答 2查看 1.5K关注 0票数 0

我遇到了一个小问题:我编写了一个通信类,它在数据到达时触发OnResponseData。现在我需要检查调用者是活动本身还是类。

请参阅以下代码:

代码语言:javascript
运行
复制
private void OnResponseData(ushort ID, byte function, byte[] values)
{
#if (winm || win7) // windows mobile or phone 7
    if (this.m_Container.Form.InvokeRequired)
        {
            this.m_Container.Form.BeginInvoke(new ModbusTCP.Master.ResponseData(OnResponseData), new object[] { id, function, values });
            return;
        }
#else
    if (??) // well this is the problem, what i need to check here?
    { 
        Action newAc;
        newAc = delegate { OnResponseData(ID, function, values); };
        this.m_Container.Form.RunOnUiThread(newAc);
        return;
    }
#endif
...

this.m_Container.Form是我的Activity,我基本上需要用于安卓的InvokeRequired。

到目前为止,谢谢。

EN

回答 2

Stack Overflow用户

发布于 2011-08-18 04:42:02

您可以查看Android.OS.Looper实例。Android.OS.Looper.MyLooper()返回与当前线程关联的Looper;如果没有Looper,则返回null。同时,Looper.MainLooper (也是Context.MainLooper)是UI线程的Looper。因此:

代码语言:javascript
运行
复制
if (Looper.MyLooper() != Looper.MainLooper)
{ 
    Action newAc;
    newAc = delegate { OnResponseData(ID, function, values); };
    this.m_Container.Form.RunOnUiThread(newAc);
    return;
}
票数 2
EN

Stack Overflow用户

发布于 2011-08-15 20:57:57

代码语言:javascript
运行
复制
 ( this.m_Container instanceOf Activity ) 

这解决了问题吗!

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/7064705

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档