活动结束时resultCode的默认值 [英] Default value for resultCode when activity finishes

查看:150
本文介绍了活动结束时resultCode的默认值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这可能是一个基本问题,但我希望能有所澄清.

This might be a basic question, but I hoping to get some clarity.

我正在尝试做的事情: 1)开始一个带有requestCode的活动,并处理两个操作 onActivityResult,一个使用RESULT_OK,另一个使用RESULT_CANCELLED. 我明确声明了它们中的每一个.

What I am trying to do: 1) Starting an activity with a requestCode, and handling two operations in onActivityResult, one using RESULT_OK, another using RESULT_CANCELLED. I explicitly state each of them.

问题是什至当我仅使用后退按钮关闭活动并且未设置任何结果时,后退堆栈中的活动接收到RESULT_CANCELLED.

The issue is even when I close the activity just using back button and not setting any result the Activity in the back stack receives RESULT_CANCELLED.

遍历源代码,我看到RESULT_CANCELLED是结果代码的默认值,并且总是将结果代码发送回去.

Going through the source code I see that RESULT_CANCELLED is the default value for the resultcode and that the resultcode is always sent back.

我读对了吗,这是一直发生的吗?还是我在应用程序中做错了什么?

Am i reading this right and is this what happens all the time? or am I doing something wrong in my application?

来源: https://github. com/android/platform_frameworks_base/blob/master/core/java/android/app/Activity.java

推荐答案

启动的Activity重新启动时,将在调用onResume()方法之前调用此Activity的onActivityResult(..)方法.检查活动文档

When your starting Activity is restarting, the onActivityResult(..) method of this Activity is called before the onResume() method is called. check Doc for Activity

默认结果代码为RESULT_CANCELLED.

And the default resultCode is RESULT_CANCELLED.

必须在已启动的Activity中显式调用setResult(int)才能更改resultCode的值.

You must explicitly call setResult(int) in the started Activity to change the value of resultCode.

这就是为什么在onActivityResult方法中检查resultCode == RESULT_OK的重要性. 因为即使您尚未调用startActivityForResult,也可以调用onActivityResult.

And that's why it's important to check resultCode == RESULT_OK in the onActivityResult method. Because the onActivityResult can be called even if you have not called startActivityForResult.

这可能会造成混淆,但这是默认的行为.

Which can be confusing, but that's the default behaviour.

  @Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    // Check which request we're responding to
    if (requestCode == YOUR_REQUEST) {
        // Make sure the request was successful
        if (resultCode == RESULT_OK) {
            // so some work
        }
    }
}

这篇关于活动结束时resultCode的默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆