gpt4 book ai didi

android - 尝试启动未注册的 ActivityResultLauncher

转载 作者:行者123 更新时间:2023-12-04 23:44:53 25 4
gpt4 key购买 nike

有时我会收到这个 IllegalStateException,它说您必须确保在调用 launch() 之前注册了 ActivityResultLauncher。但是没有方法可以检查 ActivityResultLauncher 是否已注册。我该如何解决这个问题以及为什么会发生这种情况?另外,不清楚何时调用 unregister() 方法,有什么例子吗?

最佳答案

请注意在 onCreate 中注册您的 activityResultLauncher防止副作用的方法

public class MyActiviy extends AppCompatActivity {
.
.
.

private ActivityResultLauncher<Intent> myLauncher;

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//some stuff

// Register your launcher here
myLauncher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), result -> {
if (result.getResultCode() == RESULT_OK && result.getData() != null) {
Intent data = result.getData();
}
});

findViewById(R.id.myButton).setOnClickListener(v -> {
// call `launch` after user click on button or something like that
Intent intent = new Intent(this, TargetActivity.class);
myLauncher.launch(intent);
});
}

}
引用谷歌文档:

When using the ActivityResultRegistry APIs, it's strongly recommendedto use the APIs that take a LifecycleOwner, as the LifecycleOwnerautomatically removes your registered launcher when the Lifecycle isdestroyed. However, in cases where a LifecycleOwner is not available,each ActivityResultLauncher class allows you to manually callunregister() as an alternative.


看看 Here

关于android - 尝试启动未注册的 ActivityResultLauncher,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70211364/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com