Search code examples
androidbundlejob-schedulingandroid-jobschedulertransient

Using API 26 call - transientExtras in API 23 Android


I am trying to add extras to my JobInfo.Builder supporting Android API 23 and higher. Thing is when adding Bundle to builder then I need to do builder.setTransientExtras.

ComponentName serviceComponent = new ComponentName(context, RestApiJobService.class);

JobInfo.Builder builder = new JobInfo.Builder(getUniqueJobId(), serviceComponent);

builder.setTransientExtras(RestApiJobFactory.save(jobItem);

The issue here is that builder.setTransientExtras is only supported in API 26 and higher. And builder.setExtras only supports PersistableBundle. And I need it to support Bundle since I have Files in my Bundle.

Is there any workaround to support builder.setTransientExtras in Android 23 and also the same for getTransientExtras.

Or maybe there is a way to use Bundle with bundle.setExtras().


Solution

  • Using builder.setTransientExtras can throw an IllegalArgumentException when build() is called on the JobInfo.Builder for persisted jobs. Safer to use PersistableBundle and restrict the content of the bundle to persistable types, e.g. Long, Double, String and nested PersistableBundle plus others. If you can modify the RestApiJobFactory class, instead of returning a Bundle that passes around File objects, try storing the File locations as String. If you can't, write a helper method to convert your Bundle to a PeristableBundle, extracting the File info in the process. See this answer https://stackoverflow.com/a/45178007/949224 for an example.

    The principle for persisted jobs is to reduce the extras down to basic peristable types, and when in the job itself is running, the complex transient types should be constructed.