这是我的应用的布局方式:
- onResume() 提示用户登录
- 如果用户登录,他可以继续使用该应用 <强> 3。如果用户随时退出,我想再次提示登录
我怎样才能做到这一点?
这是我的 MainActivity:
@Override
protected void onResume(){
super.onResume();
isLoggedIn = prefs.getBoolean("isLoggedIn", false);
if(!isLoggedIn){
showLoginActivity();
}
}
这是我的登录 Activity :
@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);
}
}
}
用户成功登录后:
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
Toast.makeText(getApplicationContext(), "BOOM SHAKA LAKA!",Toast.LENGTH_SHORT).show();
}
}
问题是,onResume() 是在 onActivityResult() 之前调用的,所以当用户成功登录时,我的主要 Activity 没有得到通知,因为 onResume() 是先调用的。
提示登录的最佳位置在哪里?
最佳答案
实际上,对 onActivityResult 的调用发生在 onResume 之前(参见 the docs)。您确定您实际上是在使用 startActivityForResult
开始您想要的 Activity ,并且您在将值返回给您的 Activity 之前将调用 Activity 的结果设置为 RESULT_OK
吗?尝试在您的 onActivityResult
中放置一个 Log
语句来记录该值并确保它被命中。另外,您在哪里设置 isLoggedIn
首选项的值?看来您应该在登录 Activity 中将其设置为 true
,然后再返回,但这显然没有发生。
编辑
The docs说:
You will receive this call immediately before onResume() when your activity is re-starting.
关于android - 是否在 onActivityResult() 之前调用了 onResume()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4253118/