Android 在 registerForActivityResult 中使用对象

Android use object in registerForActivityResult

在我的 AppCompatActivity 中,我声明了一个 ActivityResultLauncher。我使用 registerForActivityResult() 创建它并为 ActivityResultCallback.

传递了 LambdaExpression

但是,我需要在调用 launch().

时引用此 ActivityResultCallback 中的一个对象

示例代码:

private final ActivityResultLauncher<Intent> launcher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), result -> {
    object.doSomething();
});

method() {
    Object object = new Object();
    launcher.launch(new Intent(MainActivity.this, OtherActivity.class));
}

我可以将对象保存在 private 字段中,但这是 Android 想要我们做的吗?

我了解 Android 不希望您在不同的活动之间共享对象。但是这里,引用应该只保留在我的 MainActivity.class.

感谢任何帮助!

I could just save the object in a private field, but is this what Android intents us to do?

是的,几乎是的。查看 documentation 中的片段:

registerForActivityResult() is safe to call before your fragment or activity is created, allowing it to be used directly when declaring member variables for the returned ActivityResultLauncher instances.

所以看起来 ActivityResultCallback 应该引用声明的实例变量,所以你确实

could just save the object in a private field

这样就好了。对该对象的引用将是 private,显然,它只存在于您的 MainActivity.