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

PKu*_*mar 1 android kotlin kotlin-extension

我想使用“Kotlin”共享位于资产文件夹中的图像。如何在 android 中实现类似的代码块:

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

ant*_*ori 6

首先,您需要将数据存储在某处。如果您针对 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>
Run Code Online (Sandbox Code Playgroud)

接下来,创建一个名为的资源目录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>
Run Code Online (Sandbox Code Playgroud)

最后,您将使用 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)
Run Code Online (Sandbox Code Playgroud)

来源

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

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)))
Run Code Online (Sandbox Code Playgroud)

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

来源

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