Search code examples
androiddelayandroid-jobscheduler

Scheduling task with JobScheduler in Android causes UI freeze on app launch


While trying to find out why my android app (java) was not responding for the first 2-3 seconds after launching (UI elements were loaded, apart from menu options, but I could not click anything), I located the delay being caused by the command that schedules a task with JobScheduler.

Basically I have an App class that extends Application, and there I do set a task with JobScheduler that would run every 30 minutes and perform some action (update some information and provide notification if their value was changed).

After creating the Builder containing all details for that task, i run the command scheduler.schedule(info) and by commenting it out I found out that this is the reason my app is unresponsive for 2-3 seconds after launching.

private void scheduleJob() {
    ComponentName componentName = new ComponentName(this, myRecurringTask.class);
    JobInfo info = new JobInfo.Builder(JOB_ID, componentName)
            .setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY)
            .setPersisted(true)
            .setPeriodic(1800000)
            .build();
    JobScheduler scheduler = (JobScheduler) getSystemService(JOB_SCHEDULER_SERVICE);
    scheduler.schedule(info);
}

I have tried running it in a Thread hoping that it'll run in background and not freeze the UI while running, among other similar practices, but I have yet to manage to run it in background and not have it affect the UI's responsiveness.

I suspect that the lifecycle of the App class might be the reason of that issue but I'm not experienced enough on being sure about it, or knowing how to overcome it. Have anyone had any similar issue? And if so, how did you get it resolved?

Thank you


UPDATE 2020/02/18: As a workaround I am now checking first if job is already scheduled and only if it's not I go ahead and schedule again. When I wrote the scheduling part, I saw in the documentation that it will overwrite the job if it already exists, so I did not worry about it, but since it's affecting app's performance, it makes sense to not do it every single time.

With that being said, I'm still looking for a better solution, that's just a workaround to limit the times it gets frozen, the UI still freezes every time job gets scheduled.


Solution

  • After a lot of frustration trying to overcome the issue I was experiencing, I did a more in-depth troubleshoot where I found out that the reason app freezes is that the first job run is running right when I schedule it.

    It makes sense but I never thought of it being the issue. I have made a new question on my quest to overcome that new issue, being able to skip the first job run...

    JobScheduler - How to skip first job run of periodic job?