ActivityResultLauncher 传递自定义请求代码

Jen*_*jdn 3 android android-intent onactivityresult startactivityforresult

我有一个简单的 ActivityResultLauncher 实现,我可以在其中从图库中选择图像:

ActivityResultLauncher<Intent> actResLauncher;
actResLauncher = registerForActivityResult(   new ActivityResultContracts.StartActivityForResult(),this);
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
actResLauncher.launch(intent);
Run Code Online (Sandbox Code Playgroud)

结果:

@Override
public void onActivityResult(ActivityResult  result) {
    if(result.getResultCode()== Activity.RESULT_OK){

    }
}
Run Code Online (Sandbox Code Playgroud)

这段代码的问题是我依赖于预定义的结果代码,例如 Activity.RESULT_OK 或 Activity.RESULT_CANCELED。有没有办法在启动意图时传递自定义请求代码?

Sim*_*rma 8

首先,你不需要onActivityResult()。那条路很旧。您现在拥有用于特定目的的启动器。因此,不再需要请求代码,您现在可以按如下所示进行操作。创建一个像这样的函数:

ActivityResultLauncher<String> imageActivityResultLauncher = registerForActivityResult(
            new ActivityResultContracts.GetContent(),
            uri -> 
               //do something with uri
            });
Run Code Online (Sandbox Code Playgroud)

然后无论你想在哪里启动它,只需写:

imageActivityResultLauncher.launch("image/*");
Run Code Online (Sandbox Code Playgroud)

有关更多详细信息,请参阅此 stackoverflow 答案 /sf/answers/4455783041/