我有一个Android客户端,可以监听智能手机的传感器,当它检测到传感器值的变化时会产生一个字符串(“命令”),并创建一个套接字和一个输出流来将字符串发送到java服务器;每个传感器侦听器都创建一个套接字,其端口与其他侦听器不同。我还有一个“发送”按钮和一个文本框,可以将任何其他字符串发送到服务器。问题是,虽然按钮“发送”工作正常并且每次按下时都会发送文本框中写入的所有字符串,但每个监听器只在第一次检测到传感器值的变化时发送“命令”。 / p>
//listener buttonSend
Button.OnClickListener buttonSendOnClickListener = new Button.OnClickListener()
{
@Override
public void onClick(View arg0)
{
buttonSend.setEnabled(false);
Socket socket = null;
DataOutputStream dataOutputStream = null;
DataInputStream dataInputStream = null;
try
{
socket = new Socket(IP, 32450);
socket.setReuseAddress(true);
socket.setSoTimeout(2000);
dataOutputStream = new DataOutputStream(socket.getOutputStream());
dataInputStream = new DataInputStream(socket.getInputStream());
dataOutputStream.writeUTF(textOut.getText().toString());
textIn.setText(dataInputStream.readUTF());
}
catch (UnknownHostException e)
{
e.printStackTrace();
buttonSend.setEnabled(true);
}
catch (IOException e)
{
e.printStackTrace();
buttonSend.setEnabled(true);
}
finally
{
if (socket != null)
{
try
{
buttonSend.setEnabled(true);
socket.close();
}
catch (IOException e)
{
e.printStackTrace();
buttonSend.setEnabled(true);
}
}
if (dataOutputStream != null)
{
try
{
dataOutputStream.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
if (dataInputStream != null)
{
try
{
dataInputStream.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
}
}; //End listener buttonSend
这是按钮,所有传感器的工作方式如下:
//proximity sensor event listener
SensorEventListener proximitySensorEventListener
= new SensorEventListener()
{
public void onAccuracyChanged(Sensor arg0, int arg1)
{
// TODO Auto-generated method stub
}
public void onSensorChanged(SensorEvent arg0)
{
// TODO Auto-generated method stub
if(arg0.sensor.getType()==Sensor.TYPE_PROXIMITY && IP!="")
{
textProximitySensorData.setText("Proximity Sensor Value:"
+ String.valueOf(arg0.values[0]));
String proxValue = "Proximity Sensor: VALUE "
+ String.valueOf(arg0.values[0]);
if(buttonSend.isEnabled()==true){
Socket socket = null;
DataOutputStream dataOutputStream = null;
try
{
socket = new Socket(IP, 32452);
socket.setReuseAddress(true);
socket.setSoTimeout(2000);
dataOutputStream = new DataOutputStream(socket.getOutputStream());
dataOutputStream.writeUTF(proxValue);
}
catch (UnknownHostException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
finally
{
if (socket != null)
{
try
{
socket.close();
socket=null;
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (dataOutputStream != null)
{
try
{
dataOutputStream.close();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
}
};
我试过setSoTimeout但它没用,因为它只用于读取和setReuseAddress但它没有用,logcat和console在运行应用程序时没有显示任何错误,你能帮我找到问题吗?