2

I used to have AlarmManager + WakefulBroadcastReceiver + Service to do some background code and get location updates.

Since Oreo, this is deprecated, so now I use AlarmManager + BroadcastReceiver + JobIntentService.

And this is code for the JobIntentService in the manifest:

<service android:name="MyJobIntentService" 
 android:permission="android.permission.BIND_JOB_SERVICE"/>

And the class MyJobIntentService where I need location updates:

public class MyJobIntentService extends JobIntentService implements
        GoogleApiClient.ConnectionCallbacks,
        GoogleApiClient.OnConnectionFailedListener,
        com.google.android.gms.location.LocationListener {

private GoogleApiClient mGoogleApiClient;  
private LocationRequest mLocationRequest;

@Override
public void onCreate() {
    super.onCreate();
}

//Convenience method for enqueuing work in to this service.
static void enqueueWork(Context context, Intent work) {
    enqueueWork(context, clsJobIntentServiceDePosicionamientoPlayServices.class, 123456, work);
}


@Override
protected void onHandleWork(Intent intent) {
    // We have received work to do.  The system or framework is already holding a wake lock for us at this point, so we can just go.        
    StartLocating();
}

@Override
public void onDestroy() {
    super.onDestroy();
}


void StartLocating(){
    mGoogleApiClient = new GoogleApiClient.Builder(this)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .addApi(LocationServices.API)
            .build();
    mGoogleApiClient.connect();
}
And the rest of the location functions like onLocationChanged...

The app works (at least on the Emulator) but I am afraid I am doing something wrong because right after the onCreate(), it is called onHandleWork(), and right after that onDestroy().

A few seconds later I start getting location updates in onLocationChanged but I am afraid that something is wrong because onDestroy() has been called before. Is this the right way of doing this?

This is the way I create the JobIntentService from the BroadcastReceiver:

Intent i = new Intent(contexto, MyJobIntentService.class);
MyJobIntentService.enqueueWork(MyContext, i);
Ton
  • 9,235
  • 15
  • 59
  • 103

1 Answers1

1

JobIntentService is not what you want, it replaces an IntentService. It means that when the onHandleIntent method ends, the service is killed. In your case you need to use a foreground service or use something different.

greywolf82
  • 21,813
  • 18
  • 54
  • 108
  • I used a JobIntentService to fire Notifications to the user, when exact Alarms were triggered. What do you suggest I use now that JobIntentService is deprecated? WorkManager? – AJW Oct 17 '21 at 19:39