需要把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>