【问题标题】:Doesnt attach file to Gmail不将文件附加到 Gmail
【发布时间】:2022-01-04 22:22:40
【问题描述】:

在 kotlin 中编程并使用隐式意图。我创建了一个 txt 文件,并希望将其自动附加到有意创建的电子邮件中。此文件未附加。

binding.shareAction.setOnClickListener {
        lifecycleScope.launch {
            val sendIntent = Intent(Intent.ACTION_SEND)
            sendIntent.putExtra(Intent.EXTRA_STREAM, File("src/main/java/com/example/openlog/item_logs.txt"))
            sendIntent.type = "*/*"
            startActivity(Intent.createChooser(sendIntent, "SHARE"))
        }
    }

【问题讨论】:

  • 删除了android-studio 标签,因为该标签是针对 Android Studio 产品的问题/问题。您有一个通用的 Android 问题。

标签: android kotlin android-intent


【解决方案1】:

需要把File转成Uri。

val contentUri = FileProvider.getUriForFile(
                this,
                "com.stackkotlin.provider",  //use your app signature + ".provider"
                newFile
            )

试试下面的代码:

val newFile = getFileFromAssets(this, "demo.txt")
        val contentUri = FileProvider.getUriForFile(
            this,
            "com.stackkotlin.provider",  //use your app signature + ".provider"
            newFile
        )
        Log.e("filePath-----",""+contentUri)
        val sendIntent = Intent(Intent.ACTION_SEND)
        sendIntent.type = "*/*"
        sendIntent.putExtra(Intent.EXTRA_STREAM, contentUri)
        startActivity(Intent.createChooser(sendIntent, "SHARE"))

我正在使用资产文件,从资产文件夹获取文件。

@Throws(IOException::class)
    fun getFileFromAssets(context: Context, fileName: String): File = File(context.cacheDir, fileName)
        .also {
            if (!it.exists()) {
                it.outputStream().use { cache ->
                    context.assets.open(fileName).use { inputStream ->
                        inputStream.copyTo(cache)
                    }
                }
            }
        }

为了从文件中获取 Uri,我们需要文件提供程序

AndroidManifest.xml中添加FileProvider

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

在res->xml文件夹下添加file_paths.xml文件

<?xml version="1.0" encoding="utf-8"?>
<paths>
    <external-path
        name="external"
        path="." />
    <external-files-path
        name="external_files"
        path="." />
    <cache-path
        name="cache"
        path="." />
    <external-cache-path
        name="external_cache"
        path="." />
    <files-path
        name="files"
        path="." />
</paths>

【讨论】:

    猜你喜欢
    • 2015-11-25
    • 1970-01-01
    • 1970-01-01
    • 2019-10-11
    • 2015-09-12
    • 2021-04-04
    • 1970-01-01
    • 1970-01-01
    • 2019-08-27
    相关资源
    最近更新 更多