I am trying to implement my first JobService. I understand that a call to onStartJob
is practically guaranteed (yes there are some edges if I specify some outrageous requirements without an expiration time). But how about onStopJob
? Is it guaranteed to be called?
To be specific I have a job that will be performed in the background. But I have a way to know when the job is done (e.g. sharedPrefs). I was hoping to rely on when onStopJob is called to send a Notification to the user that the job is done.
Note: onStopJob is a convenient place for sending the notification since I am already checking whether the job is done so to know if I should retry.
p.s. Something to consider that might help (I am considering it too): If my onStartJob
returns true, how does the system know when my job stops running unless it calls onStopJob
?
Situation:
(1)onStartJob() return false.
(2)System received a cancel request after onStartJob() return false.(For example,invoke jobScheduler.cancelAll(); after onStartJob() return.)
(3)Invoke jobFinished(params,false); soon after onStartJob() return true.
(4)onStartJob() return true and requirements are no longer met.
(5)Call jobScheduler.cancelAll() after onStartJob() return true;
Keeping in mind:
onStopJob() is called if the system has determined that you
must stop execution of your job even before you've had a chance to call jobFinished().
Explain:
(1)(2)(3)System will not call onStopJob() for you job if you have tell system that you job have done by return false in onStartJob() or by call jobFinished(),because system does not have to.
(4)System will call onStopJob() for you but it will take a long time after requirements are not met,maybe 1min(test on Xiaomi 4c).
(5)System will call onStopJob() for you.
Your question:(1)how does the system know when my job stops running unless it calls onStopJob?
You can call jobFinished() or return false in onStartJob() to let system know that you have finish your job.
(2)Is it guaranteed to be called?
It is depends on situations.So it is not right to rely on onStopJob() to determine that job has done.
According to the document, onStopJob is called when system decides to stop your job forcefully before it finishs. You cannot use this API to fulfill your needs.
I suggest sending a broadcast message as a completion signal when your job finishs.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With