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:
- How can I schedule work request from a job service? I plan to convert the job service at the bottom to worker implementation.
- Once I have migrated more than one workers, then how do I schedule one worker from another? Their outcome is independent of the other, so they will have different job IDS.