gpt4 book ai didi

java - java中如何从inputStream中读取每个字符串

转载 作者:行者123 更新时间:2023-12-02 07:24:43 25 4
gpt4 key购买 nike

我正在尝试通过蓝牙将加速器值从 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 应用程序发送的每组字符串?

最佳答案

试试这个

字符串消息 = null;
BufferedReader br = 新的 BufferedReader( 新的InputStreamReader(输入流) );

msg = br.readLine();

这将解决问题

关于java - java中如何从inputStream中读取每个字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13701207/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com