android - 如何使用 Kotlin 在 Android 中共享图像?

标签 android kotlin kotlin-extension

<分区>

我想使用“Kotlin”共享 Assets 文件夹中的图像。我怎样才能在 android 中实现类似的代码块:

Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("image/jpeg");
intent.putExtra(Intent.EXTRA_STREAM, uri);
startActivity(Intent.createChooser(intent, "Share Image"));

最佳答案

首先,您需要将数据存储在某个地方。如果您针对 API 24 或更高版本进行编译,FileProvider 是一个流行的选择:

在您的 AndroidManifest.xml 中声明提供者:

<application>
  <!-- make sure within the application tag, otherwise app will crash with XmlResourceParser errors -->
  <provider
    android:name="android.support.v4.content.FileProvider"
    android:authorities="com.codepath.fileprovider"
    android:exported="false"
    android:grantUriPermissions="true">
      <meta-data
            android:name="android.support.FILE_PROVIDER_PATHS"
            android:resource="@xml/fileprovider" />
  </provider>
</application>

接下来,创建一个名为xml 的资源目录并创建一个fileprovider.xml。假设您希望授予对应用程序特定外部存储目录的访问权限,这不需要请求额外的权限,您可以按如下方式声明此行:

<?xml version="1.0" encoding="utf-8"?>
<paths>
    <external-files-path
        name="images"
        path="Pictures" />

    <!--Uncomment below to share the entire application specific directory -->
    <!--<external-path name="all_dirs" path="."/>-->
</paths>

最后,您将使用 FileProvider 类将 File 对象转换为内容提供程序:

// getExternalFilesDir() + "/Pictures" should match the declaration in fileprovider.xml paths
val file = File(getExternalFilesDir(Environment.DIRECTORY_PICTURES), "share_image_" + System.currentTimeMillis() + ".png")

// wrap File object into a content provider. NOTE: authority here should match authority in manifest declaration
val bmpUri = FileProvider.getUriForFile(MyActivity.this, "com.codepath.fileprovider", file)

Source

现在您有了一种方法来存储和检索单个文件的 Uri。下一步是简单地创建一个 Intent 并通过编写以下内容来启动它:

val intent = Intent().apply {
        this.action = Intent.ACTION_SEND
        this.putExtra(Intent.EXTRA_STREAM, bmpUri)
        this.type = "image/jpeg"
    }
startActivity(Intent.createChooser(intent, resources.getText(R.string.send_to)))

请注意 bmpUri 是您之前检索到的值。

Source

如果您运行的是 API 23 或更高版本,您应该记得考虑运行时权限。这是关于 that 的一个很好的教程.

关于android - 如何使用 Kotlin 在 Android 中共享图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48137565/

相关文章:

android - 使用未按预期检查的线程注释

android - 在 Android Java 应用程序中使用 Kotlin AAR 时出现 java.lang.NoClassDefFoundError

java - java中分割字符串值后如何更正返回值?

android - 如何将常用电子邮件域(gmail/yahoo/hotmail)的快捷方式添加到 android 电视键盘?

postgresql - 无法使用Kotlin和Spring数据保留数据

java - 如何从 Matcher<View> 获取 View

generics - 我如何在 Kotlin 中使用具有不同泛型的可变参数?

generics - 在应用程序 : problem with type inference 之前选择函数引用

generics - 具有依赖于接收器类型参数的泛型类型的 Kotlin 扩展函数(未明确指定)

android - ColorPrimaryDark 不是状态栏颜色