我的应用程序包含一个简单的 fragment ,用于打开外部网页,其中:
Intent intent = new Intent(Intent.ACTION_VIEW, externalUrl); // Uri
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
Intent chooserIntent = Intent.createChooser(intent, "Open URL...");
startActivityForResult(chooserIntent, RC_OPEN_URL);
而且,当返回结果时(在我的 Fragment 的 onActivityResult(...)
中),Fragment 会从后台弹出。但是,我现在收到了新的弃用警告:
startActivityForResult(Intent,int) in Fragment has been deprecated
我已经阅读了相应的Getting a result from an activity文档,但我不确定如何调整他们为我的特定案例提供的示例。
我发现了 ActivityResultContracts.StartActivityForResult 上课,但不知道如何通过我的
chooserIntent
给它。该类的所有在线示例似乎都在 Kotlin 中,而我尝试将它们反编译为 Java 并没有任何乐趣。所以一个Java示例说明如何使用新的 registerForActivityResult() 打开外部 URL 的方法将不胜感激。
最佳答案
没有理由使用 startActivityForResult()
createChooser()
- 你可以使用startActivity
并从 onActivityResult()
运行您的代码在您调用 startActivity
后立即:
Intent intent = new Intent(Intent.ACTION_VIEW, externalUrl); // Uri
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
Intent chooserIntent = Intent.createChooser(intent, "Open URL...");
startActivity(chooserIntent);
// Do your code from onActivityResult() here
但是,如果你真的要使用Activity Result API,那么你可以直接适配examples in the documentation ,替换示例 GetContent
与StartActivityForResult
的契约(Contract)契约(Contract):// Create this as a variable in your Fragment class
ActivityResultLauncher<Intent> mLauncher = registerForActivityResult(
new StartActivityForResult(),
new ActivityResultCallback<ActivityResult>() {
@Override
public void onActivityResult(ActivityResult result) {
// Do your code from onActivityResult
}
});
private void triggerChooser(Uri externalUri) {
Intent intent = new Intent(Intent.ACTION_VIEW, externalUrl); // Uri
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
Intent chooserIntent = Intent.createChooser(intent, "Open URL...");
mLauncher.launch(chooserIntent);
}
关于打开外部 URL 时出现 "startActivityForResult(Intent,int) in Fragment has been deprecated"的 Java 解决方案?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62613424/