开发者

Check if RunOnUiThread is necessary?

I'm stuck in a little problem: I have written a communication class th开发者_如何学运维at fires OnResponseData when data arrives. Now i need to check if the caller is the Activity itself or the class.

See this code:

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 is my Activity I basically need InvokeRequired for Android.

Thanks so far.


You can check the Android.OS.Looper instances. Android.OS.Looper.MyLooper() returns the Looper associated with the current thread; if there is no Looper, then null is returned. Meanwhile, Looper.MainLooper (and also Context.MainLooper) is the Looper for the UI thread. Thus:

if (Looper.MyLooper() != Looper.MainLooper)
{ 
    Action newAc;
    newAc = delegate { OnResponseData(ID, function, values); };
    this.m_Container.Form.RunOnUiThread(newAc);
    return;
}


 ( this.m_Container instanceOf Activity ) 

does this solve the problem !

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜