我試圖寫這個程序,更新本身的變量的當前狀態。我打算如何工作是通過定時任務來不斷髮送字符串「更新」到服務器。服務器將識別該字符串,並將在Android設備上發送變量的必要值。但是,我面臨一些問題。字符串「update」發送時沒有錯誤,但是當從服務器返回相應的值時,程序似乎無法讀取答覆。下面是代碼:從插座讀inputstreams導致Android的UI凍結
//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(); – 2012-03-20 13:41:48
嗨哈克,你能詳細解釋一下我可以如何實現嗎? 謝謝 – Pooty 2012-03-20 14:17:30
我的意思是你換成= new DataInputStream(socket.getInputStream()); InputStream is = socket.getInputStream();因爲我有它使用inputstream – 2012-03-20 14:31:48