In the actual development process, it is possible that the WorkManager initialized by the system cannot meet our conditions, and we need to customize the WorkManager.

The following code examples are based on WorkManager 2.5.0.

Remove the default initializer

To provide your own configuration, you must remove the default initializer. To do this, update androidmanifest.xml using the merge rule tools:node=”remove”.

<provider
    android:name="androidx.work.impl.WorkManagerInitializer"
    android:authorities="${applicationId}.workmanager-init"
    tools:node="remove" />
Copy the code

To realize the Configuration. The Provider

To make your Application class implements a Configuration. The Provider interface, and provide your own Configuration. The Provider. GetWorkManagerConfiguration () implementation. When you need to use WorkManager, be sure to call the method workManager.getInstance (Context). Custom getWorkManagerConfiguration WorkManager invokes the application () method to find its Configuration. (You don’t need to call workManager.initialize () yourself.)

The following example shows a custom getWorkManagerConfiguration () :

class MyApplication extends Application implements Configuration.Provider { @Override public Configuration getWorkManagerConfiguration() { return new Configuration.Builder() .setMinimumLoggingLevel(android.util.Log.INFO) .build(); }}Copy the code

WorkManager.initialize(@NonNull Context context, @NonNull Configuration configuration)

In addition to implementing configuration. Provider in the Application as described above, we can also customize the WorkManager by passing in the Configuration when the WorkManager is initialized.

        Configuration configuration = new Configuration.Builder()
                .setExecutor(Executors.newFixedThreadPool(8))
                .setMinimumLoggingLevel(Log.WARN)
                .build();
        
        WorkManager.initialize(
                MainActivity.this, configuration
                );
        WorkManager workManager = WorkManager.getInstance(MainActivity.this);
Copy the code

References:

The threading of a work | | Android Developers Android Developers (Google, cn)

Custom WorkManager configuration and initialization | | Android Developers Android Developers (Google, cn)