我想使用“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"));
我想使用“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)
现在您可以存储和检索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)))
请注意,这bmpUri
是您之前检索到的值。
如果您正在运行 API 23 或更高版本,您应该记住考虑运行时权限。这是一个很好的教程。