Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android WorkManager: Which process does work actually execute in?

I am using the WorkManager API that is supposed to be able to run even while the app isn't started or is killed(?) Then I wonder, if app isn't started or is killed, which process does the work actually execute in? Some system process? Or is it actually (by default) always running in a designated thread in the app process if nothing else is specified? I am confused. If it is running in the app process, does it start the app process without actually starting anything else in it, then?

I am curious to whether I can access my app's data from within the work while it is executing. I mean I am not supposed to be able to access for instance a singleton app member in case it is running in a completely separate process.

like image 372
JohnyTex Avatar asked Mar 02 '26 17:03

JohnyTex


1 Answers

it looks like they added multi-process support in version 2.5.0

  • see release notes for work manager version 2.5.0

steps to run worker in another process

  1. need to call setDefaultProcessName
    fun getRemoteWorkManager(context:Context):RemoteWorkManager
    {
        if (!WorkManager.isInitialized())
        {
            val configuration = Configuration.Builder()
                .setDefaultProcessName(":name_of_process")
                .build()
            WorkManager.initialize(context,configuration)
        }
        return RemoteWorkManager.getInstance(context)
    }
    
  2. need to disable the existing WorkManagerInitializer by adding below into your AndroidManifest.xml
    <manifest>
        <application>
            <provider
                android:name="androidx.startup.InitializationProvider"
                android:authorities="${applicationId}.androidx-startup"
                android:exported="false"
                tools:node="merge" >
                <meta-data
                    android:name="androidx.work.WorkManagerInitializer"
                    android:value="androidx.startup"
                    tools:node="remove" />
            </provider>
        </application>
    </manifest>
    
  3. need to enqueue work using RemoteWorkManager instead of WorkManager
  4. need to declare a new dependency to use multi-process support
    // optional - Multiprocess support
    implementation "androidx.work:work-multiprocess:$work_version"
    
  5. as per this answer, need to set the process that you want to use in the manifest for the following services
    <service
        android:name="androidx.work.multiprocess.RemoteWorkManagerService"
        tools:replace="android:process"
        android:process=":name_of_process"/>
    
    <service
        android:name="androidx.work.impl.background.systemjob.SystemJobService"
        tools:replace="android:process"
        android:process=":name_of_process"/>
    
like image 93
Eric Avatar answered Mar 05 '26 07:03

Eric