What is WorkManager
WorkManager
yesJetpack
A library in which it extendsJobScheduler
The ability to provide applications with the ability to perform tasks in the background.
It can help applications perform background tasks when conditions are met, regardless of whether the application process survives or not.
Generally, tasks that meet the following conditions are suitable for useWorkManager
implement:
- Even if the application is exited, the tasks to be executed must be guaranteed.
- Delayable tasks
- Periodic tasks
How to use WorkManager
1. Introduce related libraries
dependencies { def work_version = "2.8.0" // (Java only) implementation ":work-runtime:$work_version" // Kotlin + coroutines implementation ":work-runtime-ktx:$work_version" // optional - RxJava2 support implementation ":work-rxjava2:$work_version" // optional - GCMNetworkManager support implementation ":work-gcm:$work_version" // optional - Test helpers androidTestImplementation ":work-testing:$work_version" // optional - Multiprocess support implementation ":work-multiprocess:$work_version" }
WorkManager
The library is currently updated to2.8.0
When using the version, readers can go toWorkManager API Reference DocumentationFind the current latest version on.
2. Define a Worker
public class UploadWorker extends Worker { public UploadWorker(@NonNull Context context, @NonNull WorkerParameters params) { super(context, params); } @Override public Result doWork() { // Do the work here--in this case, upload the images. uploadImages(); // Indicate whether the work finished successfully with the Result return (); } }
Initialize a task executionUploadWorker
, inherited fromWorker
Class, indoWork
Perform the corresponding tasks in .
doWork
Return result:
-
()
: The work was completed successfully -
()
: Work failed -
()
: If the work fails, you should try it at other times according to the retry strategy
3. Create WorkRequest
CreatedWorker
After that, you need to tell the system when your task wants to be executed and what strategy to follow.
1) One-time work
WorkRequest uploadWorkRequest = new () // Additional configuration .build();
- Expedited work
2.7.0
The subsequent version introduced the concept of expedited work, and expedited processing can be set up for expedited work when performing some important tasks.
OneTimeWorkRequest request = new OneTimeWorkRequestBuilder<T>() .setInputData(inputData) .setExpedited(OutOfQuotaPolicy.RUN_AS_NON_EXPEDITED_WORK_REQUEST) .build();
Expedited processingworker
, before Android 12, it will be implemented through the foreground service, and notifications will be displayed on the notification bar, so it must be implementedgetForegroundInfo
method.
However, the expedited task does not necessarily execute immediately, and in some cases, it may still be delayed:
- System load is too high: when the system memory and other resources are insufficient
- Exceeded quota limit for expedited operations
3) Work regularly
PeriodicWorkRequest saveRequest = new (, 1, ) // Constraints .build();
4. Create constraints
Tasks will be performed only if constraints are met. If a constraint is no longer satisfied during execution,WorkManager
Will stop working.
Constraints constraints = new () .setRequiredNetworkType() .setRequiresCharging(true) .build();
5. Submit WorkRequest
WorkManager .getInstance(myContext) .enqueue(uploadWorkRequest);
useenqueue
WillWorkManager
Tasks are submitted to the system.
Multi-process WorkManager
fromWorkManager 2.6
The version starts and supports multi-process usage scenarios. Services can be set up in one process so that services are scheduled in another process.
1) Set WorkRequest
val serviceName = RemoteWorkerService:: val componentName = ComponentName(PACKAGE_NAME, serviceName) val oneTimeWorkRequest = buildOneTimeWorkRemoteWorkRequest( componentName, ExampleRemoteCoroutineWorker:: ) workManager?.enqueue(oneTimeWorkRequest)
2) Define RemoteWorkService in Manifest
<service android:name="" android:exported="false" android:process=":worker1" />
RemoteWorkerService
Don't need to create it yourself, but you need toManifest
Specifies the running process name.
You can also define your ownService
, need to be inherited fromRemoteWorkService
。
3) Java inherits RemoteListanableWorker
Java:
public class ExampleRemoteListenableWorker extends RemoteListenableWorker { private static final String TAG = "ListenableWorker"; public ExampleRemoteListenableWorker(Context appContext, WorkerParameters workerParams) { super(appContext, workerParams); } @Override public ListenableFuture<Result> startRemoteWork() { return (completer -> { (TAG, "Starting ExampleRemoteListenableWorker"); // Do some work here. return (()); }); } }
4) Kotlin inherits RemoteCoroutineWorker
Kotlin:
class ExampleRemoteCoroutineWorker(context: Context, parameters: WorkerParameters) : RemoteCoroutineWorker(context, parameters) { override suspend fun doRemoteWork(): Result { (TAG, "Starting ExampleRemoteCoroutineWorker") // Do some work here return () } companion object { private const val TAG = "CoroutineWorker" } }
Summarize
This article introducesWorkManager
How to use it, including how to use it in multiple processesWorkManager
。
WorkManager
Use tasks running in the background, even ifApp
If you fail, you must also ensure that you can complete tasks, or some scheduled tasks.
The principle of essence is also throughService
The method of pulling up the process and executing the correspondingdoWork
tasks in.
One thing to note is that if you pull the process from the background, because at this timeApp
When running in the background, you can get very few resources, and it is easy to happen in the background ANR.
AlthoughService
The backendANR
The user will not be prompted by pop-up windows, but it will affect the task execution success rate. Therefore, it is recommended to use a multi-process method to let the task run into the child process.
In the case of multi-process, it is necessary toRemoteWorkerService
During the running process, modifyApplication
In-houseonCreate
andattachBaseContext
Method, customize the initialization logic belonging to the child process.
The above is the detailed content of WorkManager to solve the problem of continuing to run background tasks after the application exits. For more information about WorkManager application exits background tasks, please pay attention to my other related articles!