开发者

Check if RunOnUiThread is necessary?

开发者 https://www.devze.com 2023-03-28 17:24 出处:网络
I\'m stuck in a little problem: I have written a communication class th开发者_如何学运维at fires OnResponseData when data arrives.

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

精彩评论

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