In my application, I am using onCreate(), for initialize of application, onStart() and onResume().
According to activity life cycle all of mentioned methods are running sequentially. In onStart() method, I have a custom dialog that when runs I take user id and password after that I send them to server and server sends me a token.
Then after taking Token I should go next step which is onResume().
but the problem is after showing dialog from onStart(), activity will go to next cycle, onResumme(). How can I say to android, “Hey guy, please don’t go to next cycle until I take token from server”?
This is my code:
@Override
protected void onStart() {
super.onStart();
Log.i("MA_onStart", "Activity is abut to start...");
.
.
.
if(!isOnline())
dialogWarning.show();
if(!isTokenValid())
dialog.show();
}
}
In this code, I call isTokenValid(). If don’t have token then I will show a dialog to take user id and password. I want activity doesn’t go to next stage until I get token. I can add while loop to wrap
if(!isTokenValid()) dialog.show();
and set a flag for breaking the loop. I can set the flag when user click yes button in dialog but I afraid that if process takes some seconds, Android kill my process and application. what is your suggestion?
Thanks
==========>
Update
I changed the code to this
gotoNextCycle = true;
while(gotoNextCycle)
if(!isTokenValid())
dialog.show();
and put gotoNextCycle = false; when user clicked yes button in dialog. As I expected, the application crashed.
What is the problem if you let Android continue with the cycle..
i mean what will happen if
onResume()is called?You should not wait in
onStart()oronResume()for responses from server.This would lead to ANR as you have observed.
You can update your app so that once you get response from server with valid token, you can refresh your view or data shown in the activity.
Maybe, let us know what information you are showing in the Activity, we can try to help you with a way to handle invalid Token case (fetch Token from server and update the information).
EDIT
you can refer the following code:
in
onClick()of the dialog (yes button) start aTreadorAsyncTaskto fetch Token from server. Meanwhile you can show a Progress dialog (“Loading… please wait” kinds).Once you get response from server, in the
ThreadorAsyncTaskdismiss this progress dialog and then calldoProcess().I assume you show some information in this activity to user based on the server response/Token. So once the Progress dialog is dismissed, your
doProcess()can update the views.If the authentication fails, then you can call
finish()on the Activity after showing someToastto user about the failure.Also make sure you call
setCancelable(false)on the Progress dialog.