83

这是我的应用程序的布局方式:

  1. onResume() 提示用户登录
  2. 如果用户登录,他可以继续使用该应用程序 3. 如果用户随时退出,我想再次提示登录

我怎样才能做到这一点?

这是我的主要活动:

@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() 首先被调用。

提示登录的最佳位置在哪里?

4

4 回答 4

105

实际上,对 onActivityResult 的调用发生在 onResume 之前(请参阅文档)。您确定您实际上是在开始您想要的活动,startActivityForResult并且您在将RESULT_OK值返回给您的活动之前将调用活动的结果设置为?尝试Log在您的语句中onActivityResult记录该值并确保它被命中。另外,您在哪里设置isLoggedIn首选项的值?似乎您应该true在登录活动返回之前将其设置为,但这显然没有发生。

编辑

文档说:

当您的活动重新开始时,您将在 onResume() 之前立即收到此调用。

于 2010-11-23T05:56:06.663 回答
31

对于片段,它甚至不像onActivityResult()在调用onResume(). 如果您要返回的活动在此期间被处理掉,您会发现对(例如)getActivity()from的调用onActivityResult()将返回 null。但是,如果该活动尚未被释放,则调用getActivity()将返回包含活动。

这种不一致可能是难以诊断缺陷的来源,但您可以通过启用开发人员选项“不保留活动”来检查应用程序的行为。我倾向于保持打开状态-我宁愿看到NullPointerException开发中的产品而不是生产中的产品。

于 2013-04-28T16:21:10.330 回答
2

您可能需要考虑从活动中抽象出登录状态。例如,如果用户可以发表评论,让 onPost 操作 ping 登录状态并从那里开始,而不是从活动状态开始。

于 2010-11-23T05:58:47.870 回答
0

像这样的回调方法onResume不适合实现所请求的功能。我建议开设一个课程并在那里添加登录/注销功能。当收到注销回调时,调用登录功能。

于 2020-10-12T10:10:02.860 回答