Skip to content

Custom Work Manager Factory Support

If your app makes use of a custom work manager factory, for example, when using hilt-worker library, you will have to make a few changes before you can use the mpos sdk successfully.

Applications that wants to handle manual initialization of work manager must implement MposWorkerDelegate in their custom application class, otherwise their application would crash at runtime.

To initialize work manager manually (maybe you want to inject some dependencies using custom [androidx.work.WorkerFactory], for example when using Dagger Hilt Worker Injection) Your application class can look like this

    class MyApp: Application, Configuration.Provider, MposWorkerDelegate {

        // This will be provided to the mpos worker, and you will also add your custom worker factories to this.
        private val delegatingWorkerFactory: DelegatingWorkerFactory = DelegatingWorkerFactory()

        override fun getWorkManagerConfiguration(): Configuration {
            return Configuration.Builder()
                .setWorkerFactory(delegatingWorkerFactory)
                .build()
        }

        override fun delegatingWorkerFactory(): DelegatingWorkerFactory {
            return delegatingWorkerFactory
        }

        // You may want to initialize your worker in the application onCreate or elsewhere.
        override fun onCreate() {
            super.onCreate()
            val myWorkerFactory = ... // Get your custom worker factor (e.g. for hilt, you would inject the HiltWorkerFactory here in the application)

            // Add your worker factory to the delegate you created above
            delegatingWorkerFactory.addFactory(myWorkerFactory)
        }
    }

That's it. Afterwards, you can just get the WorkManager instance normally by calling [androidx.work.WorkManager.getInstance] supplying the application context.

Like thus:

WorkerManager.getInstance(applicationContext)

Remember to disable default worker factory in your AndroidManifest.xml

    <provider
        android:name="androidx.startup.InitializationProvider"
        android:authorities="${applicationId}.androidx-startup"
        android:exported="false"
        tools:node="merge">
        <!-- If you are using androidx.startup to initialize other components -->
        <meta-data
            android:name="androidx.work.WorkManagerInitializer"
            android:value="androidx.startup"
            tools:node="remove" />
    </provider>