如何从两个活动之间的多个回声中返回数据?

时间:2017-04-10 16:23:50

标签: java android android-activity uart

我正在编写一个通过UART与传感器设备进行通信的Android应用程序。设备根据如下格式的4字符ASCII命令将数据发送到手机:

":" [char1] [char2] [Carriage_return](例如,":AB \ r")

我有两个活动,CalculationActivity和UartActivity。

CalculationActivity需要从UartActivity获得三个不同的传感器读数,并使用它们执行某些计算。例如,

CalculationActivity:

protected void onCreate(Bundle savedInstanceState){
    // blah, blah, blah...
    Intent i = new Intent(this, UartActivity.class);
    startActivityForResult(i, DATA_REQUEST);
}

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
     if (requestCode == DATA_REQUEST) {
         if (resultCode == RESULT_OK) {
             string sensor_data_distance = data.getStringExtra("distance");
             //need these also:
             //string sensor_data_heading = data.getStringExtra("heading");
             //string sensor_data_elevation = data.getStringExtra("elevation");
             //...
             //parse the strings and perform calculation
             //...
         }
      }
   }
}

UartActivity将命令发送到设备。收到它们后,设备回送所请求的数据,我的RX回音处理程序捕获它。例如,

UartActivity:

protected void onCreate(Bundle savedInstanceState){
    // setup and initialize UART
    String get_distance_command = ":DI\r"; //command for distance
    String get_heading_command = ":HE\r"; //command for heading
    String get_elevation_command = ":EL\r"; //command for elevation

    uartSendData(get_distance_command); //send command to TX handler

    //want to be able to send these other two:
    //uartSendData(get_heading_command);
    //uartSendData(get_elevation_command); 
}

@Override
public synchronized void onDataAvailable(){ //RX echo handler
    //blah, blah, blah...
    //get received bytes
    final String result_string = bytesToText(bytes);
    Intent i = new Intent();
    i.putExtra("distance", result_string);
    //want to be able to do this for the other two:
    //i.putExtra("heading", result_string);
    //i.putExtra("elevation", result_string);
    setResult(UartActivity.RESULT_OK);
    finish();
}

希望您可以从注释掉的代码行中推断出我在这里要完成的工作。请注意,我只能成功获得一个读数(在这种情况下为距离),但不能超过(在这种情况下为航向和高程)。

我考虑过每个命令启动UartActivity三次,但我并不喜欢这个解决方案。我宁愿只运行一次活动,发送三个命令,捕获所有回应响应,并将它们传递回CalculationActivity。这甚至可能吗?

1 个答案:

答案 0 :(得分:0)

你在setResult中缺少returnIntent。

尝试替换

setResult(UartActivity.RESULT_OK);

setResult(UartActivity.RESULT_OK, i);