68

這裏是我的應用程序是如何佈局:onActivityResult()之前調用onResume()?

  1. 的onResume()提示用戶登錄
  2. 如果在用戶登錄時,如果用戶在任何註銷,他可以繼續使用應用程式 3時間,我想再次提示登錄

我該如何做到這一點?

這裏是我的MainActivity:

@Override 
    protected void onResume(){ 
     super.onResume(); 

     isLoggedIn = prefs.getBoolean("isLoggedIn", false); 

     if(!isLoggedIn){ 
      showLoginActivity(); 
     } 
    } 

這裏是我的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); 
      } 
     } 
    } 

用戶在成功登錄後:

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()之前被調用,所以當用戶成功登錄時,我的主要活動不會得到noti因爲onResume()首先被調用。

哪裏是最好的地方提示登錄?

回答

80

對onActivityResult的調用發生在onResume之前,實際上(請參閱the docs)。你確定你真的開始了你想要的活動嗎?startActivityForResult,並且你將活動的結果設置爲RESULT_OK,然後再給你的活動返回一個值?只需在onActivityResult中輸入Log來記錄該值並確保獲得匹配。另外,您在哪裏設置isLoggedIn首選項的值?看起來您應該在登錄活動中將其設置爲true,然後再返回,但這顯然沒有發生。

+0

我在用戶登錄後設置isLoggedIn。查看我更新的代碼。不知道什麼是錯的? – 2010-11-23 06:18:02

2

您可能需要考慮從活動中抽象出登錄狀態。例如,如果用戶可以發表評論,讓onPost操作ping通登錄狀態並從那裏開始,而不是從活動狀態開始。

21

在調用onResume()之前調用onActivityResult()這樣簡單的分段。如果您正在返回的活動在此期間被處理完畢,您會發現從onActivityResult()(例如)getActivity()的呼叫將返回空值。但是,如果活動尚未處理,則致電getActivity()將返回包含活動。

這種不一致可能是難以診斷缺陷的根源,但您可以通過啓用開發人員選項「不要保留活動」來檢查應用程序的行爲。我傾向於保持這種打開 - 我寧願看到一個NullPointerException在開發中,而不是在生產中。

相關問題