我正在开发一个Android项目(Tango),它涉及从两个事件侦听器获取数据,并将这些值组合成一个JSON字符串并将其发送到服务器。
以下代码块说明了我想从中读取数据的两种方法。
mTango.connectListener(framePairs, new Tango.TangoUpdateCallback() {
@Override
public void onPoseAvailable(TangoPoseData pose) {
// Get values from pose
}
@Override
public void onPointCloudAvailable(TangoPointCloudData pointCloud) {
// Get values from pointCloud
}
}
我必须将JSON字符串发送到服务器,如下所示格式
{
pose:"pose value from onPoseAvailable",
pointCloud:"pointCloud from onPointCloudAvailable",
timeStamp:"time derived from fields available inside pose object"
}
是否有一种技术或方法可用于组合两种读数; pose和pointCloud同时在方法体中可用,这样我可以将两个值连接成一个JSON或一个字符串吗?
我可以提一点小费吗? :)非常感谢提前!
答案 0 :(得分:1)
如果你需要在发送到服务器之前调用这两个方法,你可以有2个类字段,每个回调的最后一个值,然后当调用回调方法时,它会检查另一个回调的值是的,如果是这样,将所有数据发送到服务器,如果没有,只需保留数据以便调用下一个回调。实现可能看起来像这样:
public class Foo {
private TangoPoseData mLastTangoPoseData;
private TangoPointCloudData mLastTantoPointCloudData;
public void bar() {
mTango.connectListener(framePairs, new Tango.TangoUpdateCallback() {
@Override
public void onPoseAvailable(TangoPoseData pose) {
mLastTangoPoseData = pose;
sendToServer();
}
@Override
public void onPointCloudAvailable(TangoPointCloudData pointCloud) {
mLastTantoPointCloudData = pointCloud;
sendToServer();
}
}
}
public void sendToServer() {
if (mLastTangoPoseData == null || mLastTantoPointCloudData == null) return;
makeApiCall(mLastTangoPoseData, mLastTantoPointCloudData);
mLastTangoPoseData = null;
mLastTantoPointCloudData = null;
}
}
答案 1 :(得分:1)
您可以声明JSONObject,并在方法执行时存储必需的字段,例如
private org.json.JSONObject mJSONMap = new org.json.JSONObject();
mTango.connectListener(framePairs, new Tango.TangoUpdateCallback() {
@Override
public void onPoseAvailable(TangoPoseData pose) {
// Get values from pose
mJSONMap.put("pose" , "pose value from onPoseAvailable");
mJSONMap.put("timeStamp" , "Do timestamp modifications here");
doSomethingWithMap( mJSONMap );
}
@Override
public void onPointCloudAvailable(TangoPointCloudData pointCloud) {
// Get values from pointCloud
mJSONMap.put("pointCloud" , "pointCloud from onPointCloudAvailable");
doSomethingWithMap( mJSONMap );
}
private synchronized void doSomethingWithMap( org.json.JSONObject myMap )
{
System.out.println( myMap );
// check to see if your map is populated with keys
// from onPoseAvailable() and onPointCloudAvailable()?
// We must have 3keys if BOTH THE METHOD CALLS COMPLETED
if( myMap.length() == 3 )
{
//consume the map
//Clear the map after you have consumed it
// so that future callbacks
// do not mix values associated with previous callbacks
myMap.remove("pose");
myMap.remove("timeStamp");
myMap.remove("pointCloud");
}
}
}
现在 doSomethingWithMap(org.json.JSONObject)从 onPoseAvailable(TangoPoseData)或 onPointCloudAvailable(TangoPointCloudData)调用,因此您必须还同步访问此方法。希望它能为您提供一些帮助,但如果需要,还会详细说明