Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

on Android, is onStopJob always called?

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?

like image 899
Nouvel Travay Avatar asked Jun 07 '16 21:06

Nouvel Travay


2 Answers

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.

like image 69
wanglugao Avatar answered Sep 24 '22 01:09

wanglugao


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.

like image 38
Xavier Lin Avatar answered Sep 23 '22 01:09

Xavier Lin