Notice
Recent Posts
Recent Comments
Link
«   2025/05   »
1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 31
Tags
more
Archives
Today
Total
관리 메뉴

훌륭한 개발자가 되기 위하여

[Android | Kotlin] 콘텐츠 프로바이더 이해하기 본문

안드로이드

[Android | Kotlin] 콘텐츠 프로바이더 이해하기

jay20033 2024. 1. 3. 17:03

콘텐츠 프로바이더는 앱끼리 데이터를 연동하는 컴포넌트

데이터는 보통 대상 앱의 데이터베이스나 파일 또는 앱에 할당된 메모리에 있습니다.

콘텐츠 프로바이더를 이용하면 저장소에 있는 데이터를 가져오거나 수정할 수 있습니다.

 

콘텐츠 프로바이더로 데이터 공유

콘텐츠 프로바이더 작성하기

  • 콘텐츠 프로바이더는 ContentProvider 클래스를 상속
  • onCreate( ), getType( ), query( ), insert( ), update( ), delete( ) 함수를 재정의해서 작성
// 콘텐츠 프로바이더 작성
class MyContentProvider : ContentProvider() {
    override fun delete(uri: Uri, selection: String?, selectionArgs: Array<String>?): Int {
        return 0
    }
    
    override fun getType(uri: Uri): String? {
        return null
    }
    
    override fun insert(uri: Uri, values: ContentValues?): Uri? {
        return null
    }

    override fun onCreate(): Boolean {
        return false
    }

    override fun query(
        uri: Uri,
        projection: Array<out String>?,
        selection: String?,
        selectionArgs: Array<out String>?,
        sortOrder: String?
    ): Cursor? {
        return null
    }

    override fun update(
        uri: Uri,
        values: ContentValues?,
        selection: String?,
        selectionArgs: Array<out String>?
    ): Int {
        return 0
    }
}
  • 콘텐츠 프로바이더도 안드로이드 컴포넌트이므로 매니페스트에 등록
  • name 속성뿐만 아니라 authorities 속성도 반드시 선언
  • authorities 속성은 외부에서 이 콘텐츠 프로바이더를 이용할 때 식별값
//매니페스트에 콘텐츠 프로바이더 등록
<provider
    android:authorities="com.example.test_provider"
    android:name=".MyContentProvider"
    android:exported="true"
    android:enabled="true">
</provider>

콘텐츠 프로바이더 이용하기

  • 콘텐츠 프로바이더는 인텐트와 상관이 없습니다.
  • 외부 앱에서 콘텐츠 프로바이더를 사용하려면 먼저 매니페스트에 해당 앱에 관한 패키지 공개 설정
  • 콘텐츠 프로바이더를 사용할 때는 ContentResolver 객체를 이용
    • public final int delete(Uri url, String where, String[ ] selectionArgs)
    • public final Uri insert(Uri url, ContentValues values)
    • public final Cursor query(Uri uri, String[ ] projection, String selection, String[ ] selectionArgs, String sortOrder)
    • public final int update(Uri uri, ContentValues values, String where, String[ ] selectionArgs)
<!-- 패키지 공개 설정 -->
<queries>
    <!-- 둘 중 하나만 선언하면 됩니다. -->
    <!-- <provider android:authorities="com.example.test_provider" /> -->
    <package android:name="com.example.test_outter" />
</queries>
// 시스템의 콘텐츠 프로바이더 사용
contentResolver.query(
    Uri.parse("content://com.example.test_provider"),
    null, null, null, null)
)
  • Uri 객체의 URL 문자열은 프로토콜명과 콘텐츠 프로바이더의 식별자로 등록된 authorities 값

URL 구성 / URL에 조건 설정