(Android/System) ContentProvider 기초 — 앱 간 데이터 공유


1. ContentProvider란?

앱의 데이터를 다른 앱이나 시스템에 표준화된 방식으로 공유하는 컴포넌트입니다. 연락처, 캘린더, 미디어 저장소(MediaStore)가 모두 ContentProvider로 제공됩니다.

다른 앱 / 시스템
    ↓ ContentResolver.query(uri, ...)
ContentProvider (내 앱)
    ↓ 내부적으로 DB, 파일 등 접근

앱 내부에서만 데이터를 쓴다면 필요하지 않고, 앱 간 공유가 필요할 때 사용합니다.


2. URI 구조

content://com.example.app.provider/notes/5
 └scheme  └──── authority ────────┘ └path┘└id
부분 의미
content:// 고정 scheme
authority Provider를 식별하는 고유 이름 (보통 패키지명 기반)
path 데이터의 종류 (테이블)
id 특정 행

3. Provider 구현

class NotesProvider : ContentProvider() {

    private lateinit var dbHelper: NotesDbHelper

    private val matcher = UriMatcher(UriMatcher.NO_MATCH).apply {
        addURI(AUTHORITY, "notes", NOTES)            // content://.../notes
        addURI(AUTHORITY, "notes/#", NOTE_ID)        // content://.../notes/5  (#은 숫자)
    }

    override fun onCreate(): Boolean {
        dbHelper = NotesDbHelper(context!!)
        return true
    }

    override fun query(
        uri: Uri, projection: Array<String>?, selection: String?,
        selectionArgs: Array<String>?, sortOrder: String?
    ): Cursor? {
        val db = dbHelper.readableDatabase
        val cursor = when (matcher.match(uri)) {
            NOTES -> db.query("notes", projection, selection, selectionArgs, null, null, sortOrder)
            NOTE_ID -> db.query(
                "notes", projection, "_id = ?", arrayOf(uri.lastPathSegment), null, null, sortOrder
            )
            else -> throw IllegalArgumentException("알 수 없는 URI: $uri")
        }
        cursor.setNotificationUri(context!!.contentResolver, uri)    // 변경 감지 연결
        return cursor
    }

    override fun insert(uri: Uri, values: ContentValues?): Uri? {
        require(matcher.match(uri) == NOTES) { "삽입 불가 URI: $uri" }
        val id = dbHelper.writableDatabase.insert("notes", null, values)
        context!!.contentResolver.notifyChange(uri, null)            // 관찰자에게 알림
        return ContentUris.withAppendedId(CONTENT_URI, id)
    }

    override fun update(uri: Uri, values: ContentValues?, selection: String?, args: Array<String>?): Int = TODO()
    override fun delete(uri: Uri, selection: String?, args: Array<String>?): Int = TODO()

    override fun getType(uri: Uri): String = when (matcher.match(uri)) {
        NOTES -> "vnd.android.cursor.dir/vnd.$AUTHORITY.notes"        // 여러 행
        NOTE_ID -> "vnd.android.cursor.item/vnd.$AUTHORITY.notes"     // 단일 행
        else -> throw IllegalArgumentException()
    }

    companion object {
        const val AUTHORITY = "com.example.app.provider"
        val CONTENT_URI: Uri = Uri.parse("content://$AUTHORITY/notes")
        private const val NOTES = 1
        private const val NOTE_ID = 2
    }
}

4. Manifest 등록

<provider
    android:name=".NotesProvider"
    android:authorities="com.example.app.provider"
    android:exported="true"
    android:readPermission="com.example.app.permission.READ_NOTES"
    android:writePermission="com.example.app.permission.WRITE_NOTES" />

<permission android:name="com.example.app.permission.READ_NOTES" android:protectionLevel="signature" />
<permission android:name="com.example.app.permission.WRITE_NOTES" android:protectionLevel="signature" />

protectionLevel="signature"는 같은 서명 키를 가진 앱만 접근하게 합니다. 외부에 공개하지 않을 데이터는 exported="false" 또는 signature 권한으로 보호하세요.


5. 사용하는 쪽 — ContentResolver

val resolver = context.contentResolver

// 조회
resolver.query(
    NotesProvider.CONTENT_URI,
    arrayOf("_id", "title"),
    "title LIKE ?", arrayOf("%코틀린%"),
    "_id DESC"
)?.use { cursor ->
    while (cursor.moveToNext()) {
        val title = cursor.getString(cursor.getColumnIndexOrThrow("title"))
    }
}

// 삽입
val uri = resolver.insert(NotesProvider.CONTENT_URI, ContentValues().apply {
    put("title", "새 메모")
})

// 변경 감지
resolver.registerContentObserver(NotesProvider.CONTENT_URI, true, object : ContentObserver(Handler(Looper.getMainLooper())) {
    override fun onChange(selfChange: Boolean) { reload() }
})

Cursor는 반드시 use { }로 닫아 리소스 누수를 막으세요.


6. 보안 주의 — SQL Injection

// ❌ 외부 입력을 문자열로 이어 붙이면 SQL Injection 위험
db.rawQuery("SELECT * FROM notes WHERE title = '$input'", null)

// ✅ selectionArgs로 바인딩
db.query("notes", null, "title = ?", arrayOf(input), null, null, null)

ContentProvider는 외부 앱이 selection을 직접 넘기므로 파라미터 바인딩을 강제하고, projection/sortOrder도 허용된 컬럼만 쓰도록 검증하세요.


7. 요즘 ContentProvider를 쓰는 경우

직접 구현하는 일은 드물고, 다음 상황에서 접합니다.

같은 앱 내부 데이터 접근은 Room이 훨씬 편하며, 앱 간 공유 목적이 아니라면 Provider를 만들 필요가 없습니다.


8. 정리



Related Posts