打开外部 URL 时出现 "startActivityForResult(Intent,int) in Fragment has been deprecated"的 Java 解决方案?

标签 java android android-fragments

我的应用程序包含一个简单的 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 ,替换示例 GetContentStartActivityForResult 的契约(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/

相关文章:

java - 抽屉导航上的 Back Pressed Exit 对话框 Back Pressed 不起作用

android - 状态栏下的 Material design 抽屉 : how to achieve it using a DrawerLayout with two FrameLayouts as children?

android - 我应该只使用 fragment 还是 Activity 和 fragment 的组合?

java - 如何获得今天的日期?

java - 如何启动一个java程序?

java - 数组列表。在一个索引中连接字符串值

android - 带有两个 TextView 的不可点击的 ListView 条目

java - 如何在安卓游戏中实现高分保存?

java - 这个游戏的类设计(java)

即使在交换属性后,Android 资源编译也会失败