I have multiple JobServices in my app. As per the Android docs, JobId for each JobService has to be unique per uid. In order to avoid collisions, I am using unique String hashcode as my JobId. this can lead to negative JobIds as well. Is this the right way of generating JobIds?
Asked
Active
Viewed 1,455 times
0
-
"I have multiple JobServices in my app" -- eventually, consider switching to `WorkManager`. "In order to avoid collisions, I am using unique String hashcode as my JobId... Is this the right way of generating JobIds?" -- IMHO, no. Use `final static int` values (e.g., start at `1337` and work your way up from there). Or, you could try using `id` resource values, though I am uncertain what value that adds over just using simple `int` values that you code yourself. – CommonsWare Jul 12 '18 at 12:48
-
I tried following this article also https://android-developers.googleblog.com/2017/10/working-with-multiple-jobservices.html. But I want to understand how he wants us to generate short objectId (channelId), which we can prefix with job_type. – Vivek Jul 12 '18 at 12:51
-
The code in that blog post is awful. – CommonsWare Jul 12 '18 at 12:55
-
Even i thought so. Can you please explain me how you gave the number 1337? Is it documented somewhere? – Vivek Jul 12 '18 at 12:56
-
1337 is [just a number](https://en.wikipedia.org/wiki/Leet). It has no particular meaning, other than I tend to use it for these sorts of locally-unique numbers that we need to come up with ourselves. – CommonsWare Jul 12 '18 at 12:58
-
But that does not guaranty the uniqueness of the JobId value I guess. Is there no better way we can choose a JobId? – Vivek Jul 12 '18 at 13:04
-
"But that does not guaranty the uniqueness of the JobId value I guess" -- it simply needs to be unique within your app. I don't know why you somehow need this to be *more* unique. – CommonsWare Jul 12 '18 at 21:02
-
Then should I just hardcode some int constants as JobId? – Vivek Jul 17 '18 at 09:29
-
In general, yes. Most apps only have a handful of known jobs. The post that you linked to is focused on a case where the distinct jobs is not knowable at compile time, and even then I would use a better algorithm than what they used. – CommonsWare Jul 17 '18 at 10:27
1 Answers
0
Okay so one way of doing it,maybe the only way(If you want complete automated numbers without using an arrayList of previous numbers) is to use a static field.So using this technique you'll have:
public class MyJobService extends JobService {
public static int jobIb = 0;
...
public boolean onStartJob(JobParameters jobParameters) {
jobIb++;
now each time creating a job info just use:
new JobInfo.Builder(MyJobService.jobIb,componentName).setExtras(bundle).setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY).build()
So this is the way to do it if you have only one type of JobService,if you have more simply call MyJobService.jobIb++;
on their onStartJob as well you'll be fine.

Steve Moretz
- 2,758
- 1
- 17
- 31