简体   繁体   中英

Default value for resultCode when activity finishes

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

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.

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.

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?

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

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

And the default resultCode is RESULT_CANCELLED.

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

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
        }
    }
}

您必须始终通过setResult()方法提供结果代码

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM