(Android/안드로이드) OS 기본 공유 UI로 이미지 공유하기

1. 안드로이드 앱에서 이미지를 공유할 때는 앱별 SDK를 직접 호출하지 않고,


2. 요약


3. 기본 개념: OS 기본 공유란?


4. 전체 흐름


5. Bitmap 파일 저장

fun saveBitmapToCache(context: Context, bitmap: Bitmap): File {
    val cacheDir = File(context.cacheDir, "images").apply { mkdirs() }
    val file = File(cacheDir, "share_image.png")

    FileOutputStream(file).use { out ->
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, out)
    }
    return file
}


6. FileProvider 설정

<provider
        android:name="androidx.core.content.FileProvider"
        android:authorities="${applicationId}.fileprovider"
        android:exported="false"
        android:grantUriPermissions="true">

    <meta-data
            android:name="android.support.FILE_PROVIDER_PATHS"
            android:resource="@xml/file_paths" />
</provider>

7. 파일 -> content Uri 변환

 fun shareImage(context: Context, imageUri: Uri) {
    val shareIntent = Intent(Intent.ACTION_SEND).apply {
        type = "image/*"
        putExtra(Intent.EXTRA_STREAM, imageUri)
        addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
    }

    context.startActivity(
        Intent.createChooser(shareIntent, "이미지 공유")
    )
}

8. OS 기본 공유 Intent 생성 & 호출

fun shareBitmap(context: Context, bitmap: Bitmap) {
    val file = saveBitmapToCache(context, bitmap)
    val uri = getContentUri(context, file)
    shareImage(context, uri)
}

fun shareImage(context: Context, imageUri: Uri) {
    val shareIntent = Intent(Intent.ACTION_SEND).apply {
        type = "image/*"
        putExtra(Intent.EXTRA_STREAM, imageUri)
        addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
    }

    context.startActivity(
        Intent.createChooser(shareIntent, "이미지 공유")
    )
}

9. 여러 장의 이미지 보내는 법

val uris: ArrayList<Uri> = arrayListOf(uri1, uri2)

Intent(Intent.ACTION_SEND_MULTIPLE).apply {
    type = "image/*"
    putParcelableArrayListExtra(Intent.EXTRA_STREAM, uris)
    addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
}


Related Posts