0

我正在尝试通过蓝牙将加速器值从 Android 应用程序发送到 PC。我正在开发 BluetoothChat 演示应用程序。在 Android 应用程序中,我有一个名为 onSensorChanged 的​​方法,每次加速度变化时都会调用该方法。该方法如下所示:

@Override
public void onSensorChanged(SensorEvent e) {
    // the work done when the accelerometer data changes
    try {
        Thread.sleep(25);
    } catch (InterruptedException e1) {
        e1.printStackTrace();
    }
    sensorX = e.values[0];
    sensorY = e.values[1];

    Toast.makeText(BluetoothChat.this, "x coordinate = " + sensorX + "y coordinate = " + sensorY Toast.LENGTH_SHORT).show();

    BigDecimal sensorXDec = new BigDecimal(e.values[0]).setScale(2,BigDecimal.ROUND_HALF_UP);
    BigDecimal sensorYDec = new BigDecimal(e.values[1]).setScale(2,BigDecimal.ROUND_HALF_UP);


    String vals = String.valueOf(sensorXDec.toPlainString() + "," + sensorYDec.toPlainString()); 

    mChatService.writeFromString(vals);

}

方法 writeFromString

    public void writeFromString(String temp){
    // Create temporary object
    ConnectedThread r;
    // Synchronize a copy of the ConnectedThread
    synchronized (this) {
        if (mState != STATE_CONNECTED) return;
        r = mConnectedThread;
    }
    // Perform the write unsynchronized
    r.writeString(temp);
}

writeString 方法如下:

        public void writeString(String out) {
        try {
                if(D) Log.d(TAG, "Sending File....AS STRING");
                mmOutStream.write(out.getBytes(), 0, out.getBytes().length);

        } catch (IOException e) {
            Log.e(TAG, "Exception during write", e);
        }
    }

在以下方法中,我在 PC 端处理 inputStream

    @Override
public void run() {
    try {
        // prepare to receive data
        InputStream inputStream = mConnection.openInputStream();

        System.out.println("waiting for input");

        while (true) {
            int command = inputStream.read();

            if (command == EXIT_CMD)
            {   
                System.out.println("finish process");
                break;
            }
            processCommand(command);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

问题又是:如何检索我从 Android 应用程序发送的每组字符串?

4

2 回答 2

1

试试这个

字符串味精=空;
BufferedReader br = new BufferedReader( new InputStreamReader(inputStream) );

味精 = br.readLine();

这将解决问题

于 2012-12-04T10:58:57.363 回答
1
Scanner scanner = new Scanner (inputStream);

while(true){
    if(!scanner.hasNextInt()){
        continue;
    }
    // at this point we've got an int, so get it and use it
    try{
        int commmand = scanner.nextInt();

        if (command == EXIT_CMD){
            System.out.println("finish process");
            break;
        }

        processCommand(command);
    } catch (Exception catchThem){
        // Deal with the caught exceptions
    }
}

我没有测试这个,希望它对你有用。

于 2012-12-04T11:19:22.467 回答