试试下面的代码,希望这对你有用。除了代码,您需要创建file_provider_paths.xml 并将<provider/> 标签添加到您的AndroidManifest.xml
file_provider_paths.xml
<?xml version="1.0" encoding="utf-8"?>
<paths>
<external-path
name="external_files"
path="." />
</paths>
创建file_provider_paths.xml并将上述代码放入file_provider_paths.xml文件中
AndroidManifest.xml
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="${applicationId}.fileprovider"
android:exported="false"
android:grantUriPermissions="true"
tools:replace="android:authorities">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_provider_paths"
tools:replace="android:resource" />
</provider>
将<provider/> 标签放入您的AndroidManifest.xml
MainActivity.kt
fun generatePDFFromBase64(base64: String, fileName: String) {
try {
val decodedBytes: ByteArray = Base64.decode(base64, Base64.DEFAULT)
val fos = FileOutputStream(getFilePath(fileName))
fos.write(decodedBytes)
fos.flush()
fos.close()
openDownloadedPDF(fileName)
} catch (e: IOException) {
Log.e("TAG", "Faild to generate pdf from base64: ${e.localizedMessage}")
}
}
private fun openDownloadedPDF(fileName: String) {
val file = File(getFilePath(fileName))
if (file.exists()) {
val fileProviderAuthority = "{APPLICATION_ID}.fileprovider"
val path: Uri = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
FileProvider.getUriForFile(context, mFileProviderAuthority, file)
} else {
Uri.fromFile(file)
}
val intent = Intent(Intent.ACTION_VIEW)
intent.setDataAndType(path, "application/pdf")
intent.flags = Intent.FLAG_ACTIVITY_NO_HISTORY or Intent.FLAG_GRANT_READ_URI_PERMISSION
val chooserIntent = Intent.createChooser(intent, "Open with")
try {
startActivity(chooserIntent)
} catch (e: ActivityNotFoundException) {
Log.e("TAG", "Failed to open PDF ${e.localizedMessage}")
}
}
}
fun getFilePath(filename: String): String {
val file =
File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).path)
if (!file.exists()) {
file.mkdirs()
}
return file.absolutePath.toString() + "/" + filename + ".pdf"
}