将数据从Activity传递到JobService

Amr*_*tha 8 android jobservice

我想从Activity类获取lat和经度值到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);
}
Run Code Online (Sandbox Code Playgroud)

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

Tim*_*Tim 20

在构造JobInfo对象的位置,使用setExtras()传递PersistableBundle的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();
Run Code Online (Sandbox Code Playgroud)

然后在您的JobService中,您可以使用它来检索它们

@Override
public boolean onStartJob(JobParameters params) {
    params.getExtras().getLong("lat");
    params.getExtras().getLong("lon");
}
Run Code Online (Sandbox Code Playgroud)

  • 请注意,`getBoolean()`方法只能从API 22获得.如果需要布尔值,可以将`int`作为`0`或`1`传递并从那里转换. (3认同)