Here is how my app is laid out:
- onResume() user is prompted to login
- If user logs in, he can continue using the app
3. If the user logs out at any time, I want to prompt login again
How can I achieve this?
Here is my MainActivity:
@Override
protected void onResume(){
super.onResume();
isLoggedIn = prefs.getBoolean("isLoggedIn", false);
if(!isLoggedIn){
showLoginActivity();
}
}
Here is my LoginActivity:
@Override
protected void onPostExecute(JSONObject json) {
String authorized = "200";
String unauthorized = "401";
String notfound = "404";
String status = new String();
try {
// Get the messages array
JSONObject response = json.getJSONObject("response");
status = response.getString("status");
if(status.equals(authorized)){
Toast.makeText(getApplicationContext(), "You have been logged into the app!",Toast.LENGTH_SHORT).show();
prefs.edit().putBoolean("isLoggedIn",true);
setResult(RESULT_OK, getIntent());
finish();
}
else if (status.equals(unauthorized)){
Toast.makeText(getApplicationContext(), "The username and password you provided are incorrect!",Toast.LENGTH_SHORT).show();
prefs.edit().putBoolean("isLoggedIn",true);
}
else if(status.equals(notfound)){
Toast.makeText(getApplicationContext(), "Not found",Toast.LENGTH_SHORT).show();
prefs.edit().putBoolean("isLoggedIn",true);
}
} catch (JSONException e) {
System.out.println(e);
} catch (NullPointerException e) {
System.out.println(e);
}
}
}
After the user has successfully logged in:
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
Toast.makeText(getApplicationContext(), "BOOM SHAKA LAKA!",Toast.LENGTH_SHORT).show();
}
}
The problem is, onResume() is called before onActivityResult() so when the user has successfully logged in, my main activity does not get notified because onResume() gets called first.
Where is the best place to prompt for login?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…