Check user login and launch a LoginActivity
I am wondering what is the best way to do this:
I do queries to an API which needs the user to be logged. When the application starts doing the login, if it is correct will store user/pass in preferences.
Once we are logged, if an error of NOT_LOGGED occurrs in any activity when I am trying to call the method from the API, I will retrieve user/pass from preferences and do the login again. If it's succesfull my program will try again the API query. If not, it will be open the LoginActivity. That's where I wonder what is best to do.
As the method to "Relogin" it's use fro开发者_C百科m several activities I have decided to implemented in MyApp, a class which extends from Application and keep objects alive all the activitiy's lifecycle. But I cant close the stack of activities from there, can I? My idea is to close the current stack of activities and open the Login one, using this:
if(!mMyApp.relogin(mCtx)){
Intent intent=new Intent(mCtx,ActivityLogin.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
finish();
}
But I have to call the method finish from the proper activity but not from MyApp.
So I have to repeat all the code in every single class I use the relogin(mCtx)
method.
Do you think I taclking the problem in the right way, or should I change the strategy? And BTW, what do you think is the best place to implement methods that will be called from different activities. I have been using singletons so far, but if the gc clean memory I might lose that information.
Thanks, David.
If you make relogin
take in the Activity instance (instead of a generic Context) you can invoke the finish
method in there. Try it out and see: it should work.
And in anycase when you use Intent.FLAG_ACTIVITY_CLEAR_TOP
it will automatically destroy all Activities, so the finish
is probably redundant.
精彩评论