I have an app that user submit the log in form , when it sent the data to server app create a connection for its account.
In this connection i have an integer field named as state.
the state value is : 1 for connecting, 2 for connected and 0 for failed.
I show a dialog to user display Connecting ... and then check the state of connection. if its return 0 or 2 dismiss the dialog and show the related message else if it doesn't change after 15 sec dismiss dialog and change the state to 0 !
I do the logic in this way :
final AsyncTask<IImConnection, Void, Boolean> task = new CheckSignInTask();
timeOut = new TimeOut(task);
handler.postDelayed(timeOut, 60 * 1000);
task.execute(conn);
CheckSignInTask class :
private class CheckSignInTask extends AsyncTask<IImConnection, Void, Boolean> {
private IImConnection connection;
@Override
protected Boolean doInBackground(IImConnection... params) {
try {
connection = params[0];
if (connection != null){
while (connection.getState() == ImConnection.LOGGING_IN) {
// do nothing while connection state not change
}
return true;
}
else{
return false;
}
} catch (RemoteException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
return true; //To change body of implemented methods use File | Settings | File Templates.
}
protected void onPreExecute() {
dialog = new ProgressDialog(AccountActivity.this);
dialog.setMessage("Signing in...");
dialog.show();
}
protected void onPostExecute(final Boolean result) {
if (dialog.isShowing()) {
dialog.dismiss();
}
if (result) {
try {
if (connection.getState() == ImConnection.LOGGED_IN) {
isSignedIn = true;
setResult(RESULT_OK);
finish();
} else {
isSignedIn = false;
deleteAccount();
displayLoginError("Login failed ! maybe your username/password is incorrect");
}
} catch (RemoteException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
}
else{
recreate();
}
}
@Override
protected void onCancelled() {
if (dialog.isShowing()) {
dialog.dismiss();
}
super.onCancelled();
}
}
TimeOut class :
public class TimeOut implements Runnable {
private AsyncTask task;
public TimeOut(AsyncTask task) {
this.task = task;
}
@Override
public void run() {
if (task.getStatus() == AsyncTask.Status.RUNNING) {
task.cancel(true);
deleteAccount();
try {
if (dialog != null && dialog.isShowing()) {
dialog.dismiss();
}
} catch (java.lang.IllegalArgumentException iae) {
//dialog may not be attached to window if Activity was closed
}
displayLoginError("Login failed ! check your internet connetction or maybe your username/password is incorrect");
}
}
}
Its work ! but im not sure is it a good approach ?