我想从Activity类到JobService获取经度和纬度值。我怎样才能做到这一点?我曾尝试将Intent与putExtras等一起使用(请看下面的代码),但无法正确完成。

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类别
public class MyJobService extends JobService {

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

最佳答案

在构造JobInfo对象的地方,您可以使用setExtras()来传递PersistableBundle附加功能。

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();

然后,在您的JobService中,您可以使用
@Override
public boolean onStartJob(JobParameters params) {
    params.getExtras().getLong("lat");
    params.getExtras().getLong("lon");
}

10-07 22:41