Код: Выделить всё
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.provider.DocumentsContract
import android.util.Log
import androidx.core.content.FileProvider
import java.io.File
object ShareHelper {
/**
* Share an image or PDF with other applications.
* @param context The context of the calling activity.
* @param filePath The full path to the file to be shared.
*/
fun shareFile(context: Context, filePath: String) {
val file = File(filePath)
// Check if file exists
if (!file.exists()) {
Log.e("ShareHelper", "File does not exist at $filePath")
return
}
val mimeType = when {
filePath.endsWith(".pdf", ignoreCase = true) -> "application/pdf"
filePath.endsWith(".jpg", ignoreCase = true) || filePath.endsWith(".png", ignoreCase = true) -> "image/*"
else -> {
Log.e("ShareHelper", "Unsupported file type")
return
}
}
// Create URI for the file using FileProvider (ensure you declare the provider in AndroidManifest.xml)
val fileUri: Uri = FileProvider.getUriForFile(
context,
"${context.packageName}.fileprovider", // The authority declared in AndroidManifest.xml
file
)
// Create the intent for sharing
val intent = Intent(Intent.ACTION_SEND).apply {
type = mimeType
putExtra(Intent.EXTRA_STREAM, fileUri)
addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
}
try {
context.startActivity(Intent.createChooser(intent, "Share File"))
} catch (e: Exception) {
Log.e("ShareHelper", "Error sharing file: ${e.localizedMessage}")
}
}
}
Подробнее здесь: https://stackoverflow.com/questions/796 ... are-images