【发布时间】:2014-04-03 08:14:05
【问题描述】:
我正在开发一个 Android 应用程序,由于收到响应的处理结果,我需要与服务器建立连接并更改 应用程序 UI,我正在使用 java 同步套接字编程 来处理那个连接和一个Handler 来处理UI 的变化。
每件事都在高效工作,但是当失去连接并再次重新连接时,输入被有效接收并通过处理得很好,任何依赖线程都运行完美,但是当涉及到与 UI 相关的任何事情时(即Handler,RunOnUiThread)它甚至没有进入它:
public class ConnectToServer implements Runnable {
public static Socket socket;
private BufferedReader input;
public static DataOutputStream output;
public void connect() {
try {
socket = new Socket(address, port);
} catch (Exception e) {
e.printStackTrace();
}
}
public String getServerRespons(Login login) throws JSONException { // login here is an instance of the Android Activity that i will it's methods to handle the UI changes
InputStream stream = null;
try{
stream = socket.getInputStream();
}catch(Exception e){
e.printStackTrace();
}
if(stream != null){
input = new BufferedReader(new InputStreamReader(
stream));
try {
Looper.prepare();
while (true)
{
responseLine = input.readLine();
server_response = server_response + responseLine;
//
// some processing to the server response
//
if(processing_ok){
((Login)ConnectToServer.login).sys();// this is a method in Login-Activity and it contains a regular thread that runs perfectly
try{
((Login)ConnectToServer.login).updateUI.obtainMessage(5, 0, 0, response).sendToTarget();
}
catch(Exception e){
e.printStackTrace();// nothing catched
}
System.out.println("print");//also printed without problems
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
这就是Login.Activity中的Handler:
public final Handler updateUI = new Handler(){
@Override
public void handleMessage(Message msg)
{
if(msg.what == 5){
System.out.println("here");//even that doesn't printed after reconnect
try {
response_received((String)msg.obj);
} catch (Exception e) {
e.printStackTrace();
}
}
}
};
【问题讨论】: