9

below is my demo code to start a job using FireBaseJobDispatcher.

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        FirebaseJobDispatcher dispatcher = new FirebaseJobDispatcher(new GooglePlayDriver(this));
        Job job=createJob(dispatcher);
        dispatcher.schedule(job);


    }

    public static Job createJob(FirebaseJobDispatcher dispatcher){
        Job job = dispatcher.newJobBuilder()
                // persist the task across boots
                .setLifetime(Lifetime.FOREVER)
                // Call this service when the criteria are met.
                .setService(ScheduledJobService.class)
                // unique id of the task
                .setTag("LocationJob")
                // We are mentioning that the job is not periodic.
                .setRecurring(true)
                // Run between 30 - 60 seconds from now.
                .setTrigger(Trigger.executionWindow(10,20))
                //Run this job only when the network is avaiable.
                .setConstraints(Constraint.ON_ANY_NETWORK)
                .build();
        return job;
    }
}

and below is demo Service

public class ScheduledJobService extends JobService implements GoogleApiClient.ConnectionCallbacks,GoogleApiClient.OnConnectionFailedListener,LocationListener {
    private GoogleApiClient mGoogleApiClient;
    LocationRequest mLocationRequest;

    @Override
    public boolean onStartJob(JobParameters job) {
        Log.d("token","Start Job Called");
        setUpLocationClientIfNeeded();
        mLocationRequest = LocationRequest.create();
        // Use high accuracy
        mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
        mLocationRequest.setInterval(30000);
        return true;
    }

    @Override
    public boolean onStopJob(JobParameters job) {
        Log.d("token","stopped");
        return true;
    }

    @Override
    public void onConnected(@Nullable Bundle bundle) {
        LocationServices.FusedLocationApi.requestLocationUpdates(this.mGoogleApiClient,
                mLocationRequest, this); // This is the changed line.
    }

    @Override
    public void onConnectionSuspended(int i) {

    }

    @Override
    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {

    }

    private void setUpLocationClientIfNeeded()
    {
        if(mGoogleApiClient == null)
            buildGoogleApiClient();
    }

    protected synchronized void buildGoogleApiClient() {
        this.mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API)
                .build();
        this.mGoogleApiClient.connect();
    }

    @Override
    public void onLocationChanged(Location location) {
        Log.d("token",location.getLatitude()+""+location.getLongitude());
    }
}

based on new location received i am updating location in map and once user reached destination location i want to finish job so how can i stop this job once user reaches destination and free up the resources.

Hardik Mehta
  • 867
  • 1
  • 12
  • 20

1 Answers1

9

You can call jobFinished (JobParameters params, boolean needsReschedule) in onLocationChanged(Location location). Something like the following

@Override
public void onLocationChanged(Location location) {
    Log.d("token",location.getLatitude()+""+location.getLongitude());
    if (location.getLatitude() == /*your value here*/ && location.getLongitude() == /*your value here */) {
        jobFinished(null, false);
    }
}

Hope this helps!

Omar El Halabi
  • 2,118
  • 1
  • 18
  • 26
  • @ Omar Al Halabi if framework stop my job then on stopjob will be called and to run this job again have to return true from there right ? also if i want to cancel this job from another activtity or fragment then how can we do that can you please guide on this? – Hardik Mehta May 03 '17 at 06:28
  • yes the framework will call `onStopJob` and the job will be run again if it returns true. plus if you want to cancel it from another fragment or activity I suggest to make the jobdispatcher a singleton and call `dispatcher.cancel("LocationJob");` – Omar El Halabi May 03 '17 at 08:55
  • @ Omar Al Halabi as code in start job runs on main thread is it good to request location updates from there as i have done in code above – Hardik Mehta May 03 '17 at 08:57
  • generally speaking no, but you can pass a looper as the last parameter to `requestLocationUpdates` – Omar El Halabi May 03 '17 at 09:45
  • @ Omar Al Halabi i am just requesting updates from there and sending broadcast to activity from onlocation changed method by implementing location listner. – Hardik Mehta May 03 '17 at 09:54
  • yes you can do that but this is just to reduce the overhead (in case it exists) on the main thread. so you need to switch to using loopers only if you notice that it really affects performance (which is unlikely if you don't have much handlers on the main thread) – Omar El Halabi May 03 '17 at 10:12
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/143261/discussion-between-hardik-mehta-and-omar-al-halabi). – Hardik Mehta May 03 '17 at 10:17