我正在使用套接字线程。 发送请求消息后需要大约5到10秒才能收到消息。 在那段时间我想让我的主线程显示“Please wait”弹出窗口。 程序的流程看起来像这样。套接字线程在接收时阻塞主线程
- 显示弹出
- 创建套接字线程。 - >这将连接到服务器
- 发送请求消息到服务器
- 接收消息。
我的问题是,显示弹出窗口不显示,直到套接字线程收到它的消息之后才显示出来, 。
有人可以告诉我一个解决这个问题的方法吗?
公共类LoginActivity延伸活动{
.... <some coded>
public void onClickLogin(View view) {
Log.d(this.toString(), "onClickLogin");
showLoginLoadingPopup();
String login_id = ((EditText)findViewById(R.id.login_id)).getText().toString();
String login_pwd = ((EditText)findViewById(R.id.login_pwd)).getText().toString();
conn = new Connection(handler, 1, null);
conn.start();
conn.sendData(Connection.SSPH_USERCERT, new String[] {login_id, login_pwd});
}
}
公共类连接扩展Thread实现ConnectionConstant {
private InetAddress serverAddr;
private int serverPort;
private Socket socket;
PrintWriter out;
BufferedReader in;
private Handler handler;
public Connection(Handler h, int type, ServerClass server) {
Log.d(this.toString(), "Conncetion");
setServerInfo(type, server);
handler = h;
try {
connect();
} catch (Exception e) {
Log.e(this.toString(), "Error", e);
}
}
public void run() {
Log.d(this.toString(), "run");
try {
queue();
disconnect();
} catch (Exception e) {
Log.i(this.toString(), "Information", e);
}
}
private void connect() throws Exception {
if (serverAddr != null)
Log.d(this.toString(), "connect " + serverAddr.getHostName() + "("
+ Integer.toString(serverPort) + ")");
else
Log.d(this.toString(), "connect ");
socket = new Socket(serverAddr, serverPort);
socket.setSoLinger(true, 3000);
// UTF-8
out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(
socket.getOutputStream())), true);
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
Log.i(this.toString(), "Socket connected!");
}
private void queue() throws Exception {
Log.d(this.toString(), "queue");
while (true) {
String sRcv = null;
sRcv = receive();
if (sRcv.length() > 0)
parseData(sRcv);
Thread.sleep(500);
Thread.yield();
}
}
private void send(String str) throws IOException {
Log.d(this.toString(), "send");
if (!socket.isConnected())
return;
Log.i(this.toString(), "Send : " + str);
out.println(str);
}
private String receive() throws Exception {
Log.d(this.toString(), "receive");
if (!socket.isConnected())
return null;
StringBuilder sb = new StringBuilder();
String str = "";
while ((str = in.readLine()) != null) {
Log.i(this.toString(), "Receive : " + str);
sb.append(str + "\n");
}
return sb.toString();
}
}
通过我使用JAVA的程序和Android的UI –
你可能会做错事的样子,就像调用运行** **而非** **开始在线。显示你的代码。 –
不看代码就很难说任何有用的东西。尤其是对于线程错误等。 –