【问题标题】:Pass data from Activity to JobService将数据从 Activity 传递到 JobService
【发布时间】:2017-09-08 08:56:50
【问题描述】:

我想从 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;
    }
}

【问题讨论】:

    标签: android jobservice


    【解决方案1】:

    在构造 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");
    }
    

    【讨论】:

    • 请注意,getBoolean() 方法仅适用于 API 22。如果您需要布尔值,可以将 int 传递为 0 或 1 并从那里转换。
    • 如果您需要支持低于 21 的 API,请使用 PersistableBundleCompat。
    • 像服务连接这样的对象怎么样?
    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-12
      • 1970-01-01
      • 2018-01-07
      • 1970-01-01
      • 1970-01-01
      • 2017-04-05
      相关资源
      最近更新 更多