ActivityResultLauncher注册报错:生命周期STARTED状态无法注册
问题解决:ActivityResultLauncher注册时机错误
错误原因
你遇到的MainActivity@88a859c is attempting to register while current state is STARTED错误,核心原因是在Activity进入STARTED生命周期状态后才调用registerForActivityResult()。Android系统要求ActivityResultLauncher必须在LifecycleOwner(此处为MainActivity)进入STARTED状态之前完成注册,也就是要在onCreate()方法执行阶段完成。
而你的代码中,otherActivityResultLauncher是在openOtherActivity()方法内部临时注册的,此时MainActivity已经从SomeActivity返回,处于STARTED状态,违反了系统的注册时机要求,因此报错。
解决方案
将所有ActivityResultLauncher的注册提前到onCreate()方法中,作为Activity的成员变量复用,不要在回调或点击事件方法内临时注册。
修改后的完整代码示例
public class MainActivity extends AppCompatActivity { // 声明两个Launcher作为成员变量 private ActivityResultLauncher<Intent> someActivityResultLauncher; private ActivityResultLauncher<Intent> otherActivityResultLauncher; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // 注册启动SomeActivity的Launcher someActivityResultLauncher = registerForActivityResult( new ActivityResultContracts.StartActivityForResult(), result -> { if (result.getResultCode() == 1) { Intent data = result.getData(); if (data != null) { SomeClass obj = (SomeClass) data.getSerializableExtra("Object"); openOtherActivity(obj); } } } ); // 注册启动OtherActivity的Launcher otherActivityResultLauncher = registerForActivityResult( new ActivityResultContracts.StartActivityForResult(), result -> { if (result.getResultCode() == 1) { // 处理OtherActivity返回的逻辑(如果需要) } } ); // 绑定按钮点击事件 Button someButton = findViewById(R.id.some_button); someButton.setOnClickListener(v -> { Intent someIntent = new Intent(MainActivity.this, SomeActivity.class); someActivityResultLauncher.launch(someIntent); }); } // 修改openOtherActivity方法,直接复用提前注册好的Launcher public void openOtherActivity(SomeClass obj){ Intent otherIntent = new Intent(MainActivity.this, OtherActivity.class); otherIntent.putExtra("Object", obj); otherActivityResultLauncher.launch(otherIntent); } }
关键说明
- 所有
registerForActivityResult()调用都放在onCreate()中,确保在Activity进入STARTED状态前完成注册,符合系统生命周期规范。 - 成员变量形式的Launcher可以重复使用,避免每次调用方法都创建新实例,同时也避免了生命周期冲突问题。
内容的提问来源于stack exchange,提问作者TSSK
相关产品推荐
相关产品推荐

