我正在构建一个通过套接字连接到服务器的 android 应用程序。但是我无法从工作连接线程通知主线程,因为它会锁定主线程而 android 不允许这样做。这是我的以下代码:
部分连接控制器:
public void run(){
while (true){
while (isRunning){
if (serverSocket == null){
try{
serverSocket = new Socket("*", *);
out = new PrintWriter(serverSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(
serverSocket.getInputStream()));
}
catch (IOException e){
e.printStackTrace();
}
}
if (message != ""){
try{
System.out.println(message);
out.println(message);
message = "";
reply = in.readLine();
isRunning = false;
}
catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
public void sendMessage(String path,
HashMap<String, HashMap<String, String>> variables){
this.reply = "";
isRunning = true;
String variablesJSON = JSONValue.toJSONString(variables);
this.message = path + ":" + variablesJSON;
}
认证类:
public boolean register(String email, String password, String displayName) {
String path = "User.register";
HashMap<String, String> variables = new HashMap<String, String>();
HashMap<String, HashMap<String, String>> user = new HashMap<String, HashMap<String, String>>();
String hashedPass;
try{
hashedPass = sha1(password);
}
catch (NoSuchAlgorithmException e){
e.printStackTrace();
return false;
}
variables.put("displayname", displayName);
variables.put("password", hashedPass);
variables.put("email", email);
user.put("User", variables);
connection.sendMessage(path, user, this);
final ProgressDialog progDailog = ProgressDialog.show(context,
"Please wait..", "Register", true);
new Thread(){
public void run(){
try{
while (ConnectionController.getInstance().getIsRunning()){
sleep(200);
}
progDailog.dismiss();
}
catch (Exception e){
e.printStackTrace();
}
}
}.start();
Toast.makeText(context.getApplicationContext(),
ConnectionController.getInstance().getReply(), Toast.LENGTH_LONG)
.show();
if (ConnectionController.getInstance().getReply() != "SUCCESS"){
return false;
}
return true;
}
我需要等待 ProgressDialog 完成,但是我找不到方法。我不认为 AsyncTask 是正确的方法,因为连接需要一直打开。任何提示或想法?