![](/img/trans.png)
[英]How to fix: onResume get called both before and after onActivityResult when the started activity finishes
[英]Is onResume() called before onActivityResult()?
這是我的應用程序的布局方式:
我怎樣才能做到這一點?
這是我的主要活動:
@Override
protected void onResume(){
super.onResume();
isLoggedIn = prefs.getBoolean("isLoggedIn", false);
if(!isLoggedIn){
showLoginActivity();
}
}
這是我的登錄活動:
@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() 之前被調用,所以當用戶成功登錄時,我的主要活動不會得到通知,因為 onResume() 首先被調用。
提示登錄的最佳位置在哪里?
對於片段,它甚至不像在調用onResume()
之前調用onActivityResult()
那樣簡單。 如果您要返回的活動在此期間被處理,您會發現從onActivityResult()
調用(例如) getActivity()
onActivityResult()
將返回 null。 但是,如果活動尚未處理,則調用getActivity()
將返回包含活動。
這種不一致可能是難以診斷缺陷的來源,但您可以通過啟用開發人員選項“不保留活動”來檢查應用程序的行為。 我傾向於保持打開狀態 - 我寧願在開發中看到NullPointerException
而不是在生產中。
您可能需要考慮從活動中抽象出登錄狀態。 例如,如果用戶可以發表評論,讓 onPost 操作 ping 登錄狀態並從那里開始,而不是從活動狀態開始。
像onResume
這樣的回調方法不適合實現所請求的功能。 我建議創建一個類並在那里添加登錄/注銷功能。 當收到退出回調時,調用登錄功能。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.