Im building an android application that connects to a server trough a socket. However I can't notify the mainthread from the worker connection thread, since it would lock the mainthread and android does not allow that. Here is the following code I have:
Part of connection controller:
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;
}
Authentication class:
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;
}
I need to wait for the ProgressDialog to finish, however I can't find a way. I don't think an AsyncTask is the right way todo this since the connection needs to be open all the time. Any hints or ideas?