Android setResult与onActivityResult不匹配

时间:2017-02-05 08:39:24

标签: android android-intent

我正在开展一项涉及两项活动的测验应用:一个显示QuizActivity列表的Question和一个显示问题详情的QuestionActivity(提示,选项等)。在QuizActivity我使用startActivityForResult(Intent, int)方法打开QuestionActivity,如下所示:

Intent questionIntent = new Intent(QuizActivity.this, QuestionActivity.class);
questionIntent.putExtra("currentQuestion", currentQuestion);
startActivityForResult(questionIntent, REQUEST_CODE_SELECTED_OPTION);

其中REQUEST_CODE_SELECTED_OPTION是一个设为1的常量。

QuestionActivity完成后,它应该返回所选选项的索引(假设它是一个多项选择题),所以我覆盖了onPause()回调:

@Override
public void onPause() {
    super.onPause();
    Intent returnIntent = new Intent(QuestionActivity.this, QuizActivity.class);
    if (curQuestion.selected()) {
        returnIntent.putExtra("Result Code", RESULT_OK);
        setResult(Activity.RESULT_OK, returnIntent);
        Log.d("QuestionActivity", "Returned with " + Activity.RESULT_OK);
    } else {
        returnIntent.putExtra("Result Code", RESULT_CANCELED);
        setResult(Activity.RESULT_CANCELED, returnIntent);
        Log.d("QuestionActivity", "Returned with " + Activity.RESULT_CANCELED);
    }
}

我还在onActivityResult(int, int, Intent)中实施了QuizActivity回调:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    Log.d("QuizActivity", "Received result code: " + resultCode);
    Log.d("QuizActivity", "Result code from intent: " + data.getIntExtra("Result Code", 100));
    if (requestCode == REQUEST_CODE_SELECTED_OPTION) {
        if(resultCode == Activity.RESULT_OK){
            Log.d("QuizActivity", "Got RESULT_OK");
        }
        if (resultCode == Activity.RESULT_CANCELED) {
            // do nothing
        }
    }
}

然而,当我运行应用程序时,输入QuestionActivity,选择一个选项,点击返回,从日志中我看到QuestionActivity中的结果代码正确设置为-1:

D/QuestionActivity: Returned with -1
D/QuizActivity: Received result code: 0

但在onActivityResult(int, int, Intent)方法中,结果代码为0.此外,我还尝试在传递的意图中放置int,但在QuizActivity中,收到的意图是{ {1}}。我真的很困惑。我使用的方法错了吗?

1 个答案:

答案 0 :(得分:3)

我明白了。根据此post和Android文档,必须在活动完成之前(即在调用<heap unit="MB">256</heap>setResult(int, Intent)onPause()之前调用onStop()方法我尝试将它放在onDestroy但最初没有工作,因为我在第一行调用了onBackPressed()。最后,这有效:

super.onBackPressed()