如何在使用Context的类中调用registerForActivityResult?
在持有Context的类中调用registerForActivityResult的实现方案
核心前提
registerForActivityResult 仅可在实现了LifecycleOwner接口的组件(Activity、Fragment)中完成注册,普通持有Context的业务类/工具类无法独立完成注册流程,必须依托宿主组件的生命周期完成操作。
方案1:宿主注册后传递Launcher实例
适合业务逻辑相对简单的场景,由宿主提前完成注册,将启动器实例传递给自定义类使用:
- 在Activity/Fragment中完成
ActivityResultLauncher的注册,同时可以将结果回调直接转发到自定义类中 - 自定义类持有Launcher实例,需要跳转时直接调用
launch()方法触发
示例代码:
// 宿主Activity代码 class MyActivity : AppCompatActivity() { // 注册拍照启动器 private val takePhotoLauncher = registerForActivityResult(ActivityResultContracts.TakePicture()) { result -> myCustomClass.handleTakePhotoResult(result) } // 初始化自定义类,传入Context和Launcher实例 private val myCustomClass = MyCustomClass(this, takePhotoLauncher) } // 自定义业务类代码 class MyCustomClass( private val context: Context, private val takePhotoLauncher: ActivityResultLauncher<Uri> ) { fun takePhoto(targetUri: Uri) { // 触发系统拍照 takePhotoLauncher.launch(targetUri) } fun handleTakePhotoResult(isSuccess: Boolean) { // 处理拍照结果逻辑 } }
方案2:自定义类实现LifecycleObserver自动注册
适合自定义类需要和宿主生命周期绑定的场景,不需要手动传递Launcher实例:
- 自定义类实现
LifecycleObserver接口,接收宿主的LifecycleOwner实例 - 在宿主
ON_CREATE生命周期节点完成Launcher的注册,内部自行处理结果
示例代码:
// 自定义业务类代码 class MyCustomClass( private val context: Context, private val lifecycleOwner: LifecycleOwner ) : LifecycleObserver { private lateinit var takePhotoLauncher: ActivityResultLauncher<Uri> init { // 绑定宿主生命周期 lifecycleOwner.lifecycle.addObserver(this) } @OnLifecycleEvent(Lifecycle.Event.ON_CREATE) fun onHostCreate() { // 在宿主创建阶段注册启动器 takePhotoLauncher = lifecycleOwner.registerForActivityResult(ActivityResultContracts.TakePicture()) { isSuccess -> // 直接内部处理拍照结果 } } fun takePhoto(targetUri: Uri) { takePhotoLauncher.launch(targetUri) } } // 宿主Activity初始化代码 class MyActivity : AppCompatActivity() { private val myCustomClass = MyCustomClass(this, this) }
注意事项
- 注册操作必须在宿主
ON_START生命周期之前完成,禁止在点击事件等运行时异步逻辑中调用registerForActivityResult,否则会抛出运行时异常- 不要将
ActivityResultLauncher实例传递给生命周期长于宿主的类,避免引发内存泄漏- 若持有的Context是ApplicationContext,无法直接用于注册,必须依托可见的Activity/Fragment作为LifecycleOwner载体
内容的提问来源于stack exchange,提问作者allim
相关产品推荐
相关产品推荐

