我正在开发一个 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
中的处理程序:
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();
}
}
}
};
最佳答案
我建议您通过触发 ConnectToServer 类中的接口(interface)来更新 Activity 或 fragment 中的 UI 元素。
在您的登录 Activity 中,实现 LoginInterface 并使用如下结构创建对象:
new ConnectToServer(this);
并创建一个界面
public interface LoginInterface {
abstract void onLoginProcessFinished(String message);
}
在 ConnectToServer 类中,声明一个接口(interface)
LoginInterface loginInterface;
和你的构造函数
公共(public)ConnectToServer(LoginInterface登录接口(interface)){ this.loginInterface = 登录接口(interface); }
然后当您完成连接后,
if(processing_ok){
loginInterface.onLoginProcessFinished(response);
}
您的 connectToServer 将在您实现接口(interface)的登录 Activity 中触发 onLoginProcessFinished,因此您将在您更新 UI 的 Activity 中拥有一个名为 onLoginProcessFinished 的方法。
关于java - 重新连接到服务器后无法处理 UI,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22831612/