【发布时间】:2012-03-20 13:23:14
【问题描述】:
我正在尝试编写这个程序,它会根据变量的当前状态进行自我更新。我打算如何工作是通过定时任务不断将字符串“update”发送到服务器。服务器将识别该字符串并在 android 设备上发送变量的必要值。但是,我面临一些问题。字符串“update”正在发送而没有错误,但是当从服务器发回相应的值时,程序似乎无法读取回复。代码如下:
//Open socket and initialize data streams
try {
socket = new Socket(serverIpAddress, applicationport);
//in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
//in = new DataInputStream(socket.getInputStream());
out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(
socket.getOutputStream())), true);
} catch (UnknownHostException ex) {
// TODO Auto-generated catch block
ex.printStackTrace();
ShowDialog("Login Error" + ex.getMessage());
} catch (IOException ex) {
// TODO Auto-generated catch block
ex.printStackTrace();
ShowDialog("Login Error" + ex.getMessage());
}
//Create new daemon timer
updateData = new Timer(true);
updateData.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
out.println("update");
UpdateMethod();
}//run
}, 1000, 10000);//schedule the delays start/interval here
};
private void UpdateMethod() {
//This method is called directly by the timer
//and runs in the same thread as the timer.
//It calls the method that will work with the UI
//through the runOnUiThread method.
this.runOnUiThread(Timer_Tick);
};//timermethod
private Runnable Timer_Tick = new Runnable() {
public void run() {
try {
//in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
//String getx1 = null;
//getx1 = in.readLine();
//if (getx1 != null) {
//float updatex1 = Float.parseFloat(getx1);
//get_x1 = getx1;
//}
in = new DataInputStream(socket.getInputStream());
/*try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}*/
x1display = (TextView) findViewById(R.id.x1display);
x1display.setText(in.readUTF());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally {
if (in != null){
try {
in.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
};
如您所见,我也尝试过使用 DataInputStream 和 BufferedReader,但无济于事。
编辑:似乎尝试从输入流中读取导致我的 UI 冻结。我不知道出了什么问题,因为我的代码似乎没有错误..
任何帮助或建议将不胜感激!
谢谢!
【问题讨论】:
-
你试过用:InputStream is = socket.getInputStream();
-
嗨哈克姆,你能更详细地解释一下我如何实现这个吗?谢谢
-
我的意思是你替换 = new DataInputStream(socket.getInputStream());与 InputStream 是 = socket.getInputStream();因为我让它使用输入流工作
标签: java android sockets timer inputstream