I have read the following post on WorkManager about scheduling worker from another worker. I am attempting to convert our job services, which are written in Java, to WorkManager in Kotlin.
In our current code base, when a job service is invoked, it can conditionally invoke another job service.
I have a custom job service which fetches Firebase token in the background as follows:
public class FirebaseJobService extends JobService {
@Override
public boolean onStartJob(@NonNull final JobParameters jobParameters) {
// Fetch Firebase token
String firebaseToken = FirebaseInstanceId.getInstance().getToken(
"12345" // Unique sender Id
"FCM"
);
// Persist fcm token to local sqlite db.
// Make another request to activate token on our backend. This is handled by another job service.
}
}
This service is currently invoked by another service given below
public class MyCustomJobService extends JobService {
@Override
public void onStartJob(@NonNull final JobParameters jobParameters) {
. . . . .
boolean isForceActivationRequired = checkIfForceActivationRequired();
String userId = getUserId(); // Helper function to get the user ID.
// How can I call this service
if (isForceActivationRequired) {
PersistableBundle bundle = PersistableBundle();
bundle.putString("userId", userId);
bundle.putBoolean("forceActivation", isForceActivationRequired);
JobInfo.Builder jobInfoBuilder = new JobInfo.Builder(1500, new ComponentName(context, FirebaseJobService.class));
jobInfoBuilder.setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY);
jobInfoBuilder.setExtras(persistableBundle);
// Schedule the job
final JobScheduler scheduler = (JobScheduler) getSystemService(Context.JOB_SCHEDULER_SERVICE);
scheduler.schedule(jobInfoBuilder.build());
}
}
}
I am trying to convert MyCustomJobService
to use WorkManager library and subsequently all the other job services as well. My questions are as follows:
This might be a solution for you.
val workRequest: WorkRequest = OneTimeWorkRequestBuilder<YourNewWorker>().build()
WorkManager.getInstance(context).enqueue(workRequest)
This can be used in your JobService
or another worker that you have. I do not recommend running a worker from another worker without thoroughly testing the code and verifying your retry policy along with any other options you setup for the work request. There could be adverse side effects that happen.