Search code examples
androidbroadcastreceiverfirebase-job-dispatcherjobservice

Broadcast receiver doesn't work after registering in onStartJob


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");
  }

Solution

  • My problem was that I forgot to initialize screenBroadcastin onStartJob() after checking if it's null. Also I was returning false in onStartJob() instead of true.

    From Docs:

    Returning false from this method means your job is already finished. The system's wakelock for the job will be released, and onStopJob(android.app.job.JobParameters) will not be invoked.

    And:

    Return true from this method if your job needs to continue running. If you do this, the job remains active until you call jobFinished(android.app.job.JobParameters, boolean) to tell the system that it has completed its work, or until the job's required constraints are no longer satisfied.

    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.