Pass data from Activity to JobService

8.5k views Asked by At

I want to get lat and longitude value from Activity class to JobService. How can I do that? I'd tried using Intent with putExtras etc(please have a look at the code below) but could not make it right.

MainActivity.class

protected void createLocationRequest(Bundle bundle) {

    LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, new LocationCallback() {
        @Override
        public void onLocationResult(final LocationResult locationResult) {
            Log.i("onLocationResult", locationResult + "");
            latitude = locationResult.getLastLocation().getLatitude() + "";
            longitude = locationResult.getLastLocation().getLongitude() + "";
            Log.e("onLocationResult lat", latitude);
            Log.e("onLocationResult Lon", longitude);
            //I need to send latitude and longitude value to jobService? 
            //how to do that?

        //tried using intent but didn't seem to work
            //Intent mIntent = new Intent();
            //mIntent.putExtra("lat", latitude);
            //mIntent.putExtra("lon", longitude);
        }
    }, null);
}

MyJobService class

public class MyJobService extends JobService {

    @Override
    public boolean onStartJob(JobParameters jobParameters) {
        //I need to get latitude and longitude value here from mainActivity 
        return true;
    }
}
2

There are 2 answers

3
Tim On BEST ANSWER

Where you construct the JobInfo object, you use setExtras() to pass a PersistableBundle of extras.

ComponentName componentName = new ComponentName(context, MyJobService.class);

PersistableBundle bundle = new PersistableBundle();
bundle.putLong("lat", lat);
bundle.putLong("lon", lon);

JobInfo jobInfo = new JobInfo.Builder(0, componentName)
        .setExtras(bundle)
        .build();

Then in your JobService you can retrieve them with

@Override
public boolean onStartJob(JobParameters params) {
    params.getExtras().getLong("lat");
    params.getExtras().getLong("lon");
}
0
TwinkalGajera On

you can store these data in Shared preferences, and when onStartJob() method call you can access Lat long data from there.

you can also update share preference values as per latest location lat long values and get latest lat long when service will run.