将数据从Activity传递到JobService

时间:2017-09-08 08:56:51

标签: 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);
}

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;
    }
}

2 个答案:

答案 0 :(得分:15)

在构造JobInfo对象的地方,使用setExtras()传递一个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();

然后在您的JobService中,您可以使用

检索它们
@Override
public boolean onStartJob(JobParameters params) {
    params.getExtras().getLong("lat");
    params.getExtras().getLong("lon");
}

答案 1 :(得分:0)

您可以将这些数据存储在共享首选项中,当onStartJob()方法调用时,您可以从那里访问Lat long数据。

您还可以根据最新的位置lat long值更新共享偏好值,并在服务运行时获取最新的lat。