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在开发中,而不是在生产中。

相关问题