从onLocationChanged方法获取服务的纬度/经度

时间:2017-09-18 19:46:55

标签: java android gps

我有一个名为GPS_Service的服务。 来自其他活动我想启动此服务,并从onLocationChanged()方法获取location.getLatitude()和location.getLongitude()的值。如果onLocationChanged()不是静态的,我怎么能这样做?

提前致谢!

public class GPS_Service extends Service {

private LocationListener listener;
private LocationManager locManager;

@Nullable
@Override
public IBinder onBind(Intent intent) {
    return null;
}

@Override
public void onCreate() {
    liveLocs = new ArrayList<>();
    if (PreferenceManager.getDefaultSharedPreferences(GPS_Service
            .this).getString("len_live_locations", "-") != "-") {

    }

    listener = new LocationListener() {
    @Override
        public void onLocationChanged(Location location) {
            Intent i = new Intent("location_update");
            i.putExtra("coordinates", location.getLongitude() + "       " + location
                    .getLatitude());
            sendBroadcast(i);
        }
    }
}

2 个答案:

答案 0 :(得分:1)

在您的服务中尝试此操作:尝试使用Bundle

Intent intent = new Intent("YourAction");
Bundle bundle = new Bundle();
bundle.put... // put extras you want to pass with broadcast. This is optional
bundle.putString("valueName", "The value you want in the activity");
bundle.putDouble("doubleName", someDouble);
intent.putExtras(bundle)
LocalBroadcastManager.getInstance(context).sendBroadcast(intent);

答案 1 :(得分:0)

这可能令人难以置信的错综复杂。您必须决定使用哪种类型的位置提供商,获取权限,检查他们是否安装了Google Play服务以及所需的正确版本,当然还有位置管理器与融合位置管理器等的后备选项。

我花了很多时间在监控位置周围编写库,它可能会花费大量的时间和维护,有时可能会有点痛苦。

所以这就是我的建议。你提到过&#34; Service&#34;我不知道这是否是你真正需要的,但你可以做三件事之一。

  1. 使用单件包装器管理位置
  2. 创建一个IntentService,让您的位置在令人满意的精度范围内考虑完成,然后广播使用自定义广播接收器接收您的更改
  3. 创建一个常规的Android服务,可以继续更新该位置,并根据需要从您需要绑定到此服务的后台将其反馈给您,由您来启动和停止它。但请注意,在后台收集位置存在限制,现在可能需要在任务栏中发送粘性通知。
  4. 我建议你从单个包装器中的一个好的库开始,使用简单的回调,然后从那里开始进入服务包装器。我个人喜欢这个库来进行位置更新。

    https://github.com/mrmans0n/smart-location-lib

    效果很好。古德勒克。