我用C#开发了一个基于 PC 的 API来与嵌入式电子设备进行通信。此 API 读取 PC COM 端口、解码数据包、构建数据包并引发事件。现在我需要在 Android 手机中开发相同的 API。由于 C# 和 Java 事件之间存在差异,我很困惑如何在 Java 中实现相同的目标。
以下 C# 代码引发事件:
public class MARGserial
{
dataObject = BT_DeconstructPacket(encodedPacket);
if (dataObject != null) // if packet successfully deconstructed
{
OnMARGdataReceived(dataObject);
if (dataObject is RawMARGdata)
{
OnRawMARGdataReceived((RawMARGdata)dataObject);
PacketsReadCounter.RawMARGdataPackets++;
}
}
public delegate void onRawMARGdataReceived(object sender, RawMARGdata e);
public event onRawMARGdataReceived RawMARGdataReceived;
protected virtual void OnRawMARGdataReceived(RawMARGdata e)
{
if (RawMARGdataReceived != null)
RawMARGdataReceived(this, e);
}
}/*End of MARGserial class */
以下代码用于OnRawMARGdataReceived
在 Windows 控制台应用程序中订阅 Event。
public static MARG_api.MARGserial MARGserial = new MARG_api.MARGserial("COM44");
MARGserial.RawMARGdataReceived += new MARG_api.MARGserial.onRawMARGdataReceived(MARGserial_RawMARGdataReceived);
static void MARGserial_RawMARGdataReceived(object sender, MARG_api.RawMARGdata e)
{
Console.WriteLine("Data : " + e.Accelerometer[0].ToString() + " "+e.Accelerometer[1].ToString()+ " "+e.Accelerometer[2].ToString());
}
对于 Android Java 应用程序,应用程序本身的 Main Activity 类必须订阅在另一个类线程内触发的事件(该线程读取蓝牙缓冲区并构造数据包)