4

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

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

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 权限的原因相同。

还有其他方法可以在即时应用程序中共享图像吗?

4

3 回答 3

1

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

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

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

于 2019-07-23T14:14:14.703 回答
0

您可以使用Intent类共享任何内容

Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_TEXT, "Image URL");
startActivity(intent);
于 2019-07-23T11:32:52.287 回答
0

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

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!"));
}
于 2019-07-23T10:27:33.403 回答