onStartJob and onStopJob Not Working in android to run background Thread

本秂侑毒 提交于 2019-12-06 15:13:05
Sagar

There were some issues with setPeriodic() on Android Version < N (Although I don't have official link to issue). You need to use setMinimuLatency() to make it work across all version

    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
        jobInfo = new JobInfo.Builder(id, name)
                .setMinimumLatency(5000)
                .setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY)
                .setPersisted(true)
                .build();
    } else {
        jobInfo = new JobInfo.Builder(id, name)
                .setPeriodic(5000)
                .setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY)
                .setPersisted(true)
                .build();
   }

working fine but time is taking longer than 5 second to execute again

Based on the documentation for setMinimumLatency():

Milliseconds before which this job will not be considered for execution

Based on the documentation for setPeriodic():

You have no control over when within this interval this job will be executed, only the guarantee that it will be executed at most once within this interval

Overall you cannot control when the scheduled job will be executed. The system will decide when to execute it.

In my code I want to check and send FCM notification after every 5 minutes even app is active or not

Its not a great idea to do it. You can never guarantee that you will successfully execute the task ever 5 minutes when the doze mode kicks in.

Although there are alternatives like creating foreground service or triggering your AlarmManager every 5 minutes, but these approaches will drain battery.

You can instead reduce the frequency with which you notify your server. Lets say every 2 hours or twice in a day. But using JobScheduler you won't be able to pin point the exact time. If your requirement is exact time, then go for AlarmManager. Refer this link to check how it can be achieved

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!