我正在构建一个通过套接字连接到服务器的Android应用程序。但是我无法从工作者连接线程通知mainthread,因为它会锁定mainthread并且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是正确的方式,因为连接需要一直打开。任何提示或想法?
答案 0 :(得分:1)
AsyncTask是处理此问题的正确方法。以及您需要对UI执行的所有操作,请使用onPost
方法执行此操作。事实上,如果您想在活动中调用异步并从同一活动更新视图
我使用技巧2,让事情有效。一旦我让它们工作,我将AsyncTask
取出,然后使用BroadcastReceiver。只是为了简化我的开发和演示时间:)