您如何通过即时应用程序中的意图共享图像?

How do you share images via an intent in an instant app?

我们正在构建一个测验即时应用程序,用户可以在其中完成测验,然后分享他们的结果。我们与 link 共享一些文本,以及显示用户测验结果的图像。当我们在安装的应用程序中执行此流程时没有问题,但是在即时应用程序中,图像无法共享。

以下是我们生成意图的方式:

val uri = FileProvider.getUriForFile(context, "${context.packageName}.fileprovider", image)
val shareIntent = Intent().apply {
    action = Intent.ACTION_SEND
    putExtra(Intent.EXTRA_TEXT, content)
    putExtra(Intent.EXTRA_STREAM, uri)
    type = "image/*"
    addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
}
activity?.startActivity(Intent.createChooser(shareIntent, getString(R.string.quiz_share_title)))

这是我们的基本应用程序清单中的提供程序:

<provider
    android:name="androidx.core.content.FileProvider"
    android:authorities="${applicationId}.fileprovider"
    android:exported="false"
    android:grantUriPermissions="true">
    <meta-data
        android:name="android.support.FILE_PROVIDER_PATHS"
        android:resource="@xml/fileprovider" />
</provider>

当用户在免安装应用中分享图片时,此错误信息出现在logcat:

java.lang.SecurityException: Permission Denial: reading androidx.core.content.FileProvider uri content://com.redacted.fileprovider/shared/1563809004297.png from pid=29184, uid=1000 requires the provider be exported, or grantUriPermission()

我已经尝试设置 exported="true",这会导致即时应用程序在启动时崩溃,但出现以下异常:

java.lang.RuntimeException: Unable to get provider androidx.core.content.FileProvider: java.lang.SecurityException: Provider must not be exported

我猜免安装应用不能使用 FLAG_GRANT_READ_URI_PERMISSION 标志,原因与它们不能使用 WRITE_EXTERNAL_STORAGE 权限相同。

我们可以通过其他方式在免安装应用中分享图片吗?

使用这段代码从目录共享图像:

private void shareImage() {
    Intent share = new Intent(Intent.ACTION_SEND);

    // If you want to share a png image only, you can do:
    // setType("image/png"); OR for jpeg: setType("image/jpeg");
    share.setType("image/*");

    // Make sure you put example png image named myImage.png in your
    // directory
    String imagePath = Environment.getExternalStorageDirectory()
            + "/myImage.png";

    File imageFileToShare = new File(imagePath);

    Uri uri = Uri.fromFile(imageFileToShare);
    share.putExtra(Intent.EXTRA_STREAM, uri);

    startActivity(Intent.createChooser(share, "Share Image!"));
}

您可以使用 Intent class

分享任何内容
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_TEXT, "Image URL");
startActivity(intent);

免安装应用不能导出 ContentProvider。这是一个安全限制,在这里崩溃的应用程序按预期工作。

您可以在触发 Intent 之前使用 InstantApps.showInstallPrompt(),以便让用户在执行此操作之前安装应用程序。请确保您显示的消息包含您的理由,否则您可能会使您的用户感到困惑。

还有其他方法可以使用免安装应用分享图片。但这些取决于图像的来源。如果是外部内容提供商(即相机应用程序),您应该能够转发 URI。