I use FirebaseJobDispatcher and JobService to do some work on the background. Mainly I want to register to a screen on/off receiver. When the job is called for the first time the receiver is registered as it supposed.
However, immediately after onStartJob(), onDestroy() is called and according to the logs, the receiver is null. If I try to trigger the screen to turn on/off I don't see any logs from the receiver. What am I doing wrong here?
In onStratJob() I have the following code:
public boolean onStartJob(@NonNull JobParameters job) {
Log.i(JobFormActivity.TAG, "onStartJob() called");
if (screenBroadcast == null){
Log.e(JobFormActivity.TAG, "onStartJob() --> receiver is null, registering receiver");
IntentFilter screenStateFilter = new IntentFilter();
screenStateFilter.addAction(Intent.ACTION_SCREEN_ON);
screenStateFilter.addAction(Intent.ACTION_SCREEN_OFF);
registerReceiver(screenBroadcast, screenStateFilter);
}
return false;
}
In onStopJob() I have the following code:
@Override
public boolean onStopJob(@NonNull JobParameters job) {
Log.e(JobFormActivity.TAG, "onStopJob() called");
if(screenBroadcast != null) {
Log.e(JobFormActivity.TAG, "onStopJob() --> receiver is not null, unregistering receiver");
unregisterReceiver(screenBroadcast);
}
return false;
}
In onDestroy() I have the following code:
public void onDestroy() {
super.onDestroy();
Log.e(JobFormActivity.TAG, "onDestory()");
if(screenBroadcast != null)
Log.e(JobFormActivity.TAG, "onDestroy() --> receiver is not null");
else
Log.e(JobFormActivity.TAG, "onDestory() --> receiver is null");
}
My problem was that I forgot to initialize
screenBroadcastinonStartJob()after checking if it'snull. Also I was returningfalseinonStartJob()instead oftrue.From Docs:
And:
In my case, since I needed the broadcast receivers to be alive, I needed to return true so that onDestroy wouldn't be called and the receivers wouldn't unregister.