모바일 앱(안드로이드)

Android에서 WorkManager를 InitializationProvider로 설정하기

Billcorea 2024. 10. 21. 15:04
반응형

Android에서 WorkManager를 InitializationProvider로 설정하기

worker ?

 

안녕하세요! 이번 포스트에서는 Android에서 WorkManager를 InitializationProvider를 사용하여 수동으로 초기화하는 방법에 대해 알아보겠습니다.

1. WorkManager 의존성 추가

먼저, build.gradle 파일에 WorkManager와 AndroidX Startup 라이브러리 의존성을 추가합니다:

gradle
dependencies {
    implementation "androidx.work:work-runtime-ktx:2.9.1"
    implementation "androidx.startup:startup-runtime:1.1.1"
}

2. InitializationProvider 클래스 정의

WorkManager를 초기화할 InitializationProvider 클래스를 작성합니다:

kotlin
import android.content.Context
import androidx.startup.Initializer
import androidx.work.Configuration
import androidx.work.WorkManager

class WorkManagerInitializer : Initializer<WorkManager> {
    override fun create(context: Context): WorkManager {
        val configuration = Configuration.Builder()
            .setWorkerFactory(KoinWorkerFactory())
            .build()
        WorkManager.initialize(context, configuration)
        return WorkManager.getInstance(context)
    }

    override fun dependencies(): List<Class<out Initializer<*>>> {
        return emptyList()
    }
}

3. AndroidManifest.xml 설정

AndroidManifest.xml 파일에서 InitializationProvider를 구성합니다:

xml
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools">

    <application
        android:name=".di.MainApplication"
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher_v1"
        android:label="@string/app_name"
        android:theme="@style/Theme.BLE_First_APP_1001">

        <!-- InitializationProvider 설정 -->
        <provider
            android:name="androidx.startup.InitializationProvider"
            android:authorities="${applicationId}.androidx-startup"
            android:exported="false"
            tools:node="merge">
            <meta-data
                android:name="com.billcorea.bluetooth1001.di.WorkManagerInitializer"
                android:value="androidx.startup" />
        </provider>
    </application>
</manifest>

4. Worker 클래스 정의

백그라운드에서 수행할 작업을 정의하기 위해 Worker 클래스를 생성합니다:

kotlin
import android.content.Context
import androidx.work.Worker
import androidx.work.WorkerParameters
import org.koin.core.component.KoinComponent
import org.koin.core.component.inject

class SyncWorker(context: Context, params: WorkerParameters) : Worker(context, params), KoinComponent {
    private val deviceInfoDao: DeviceInfoDao by inject()

    override fun doWork(): Result {
        // 데이터베이스 작업 수행
        val devices = deviceInfoDao.getAllDevices()
        return Result.success()
    }
}

5. 주기적인 작업 설정

주기적인 작업을 설정하기 위해 PeriodicWorkRequest를 사용할  있습니다:

kotlin
import androidx.work.PeriodicWorkRequestBuilder
import androidx.work.WorkManager
import java.util.concurrent.TimeUnit

val periodicSyncWorkRequest = PeriodicWorkRequestBuilder<SyncWorker>(15, TimeUnit.MINUTES).build()
WorkManager.getInstance(context).enqueue(periodicSyncWorkRequest)

이렇게 하면 AndroidX Startup 라이브러리를 사용하여 WorkManager를 수동으로 초기화하고, Worker를 설정하여 주기적인 작업을 수행할  있습니다. 궁금한 점이 있으면 언제든지 댓글로 남겨주세요! 😊



반응형