在后台服务中使用Google Play服务LocationClient

我的应用程序旨在定期跟踪用户的位置,并将其发送到服务器,最近我改变了我的代码与谷歌播放服务的位置API。

我创build了locationClient并连接到onStartCommand中的服务

public int onStartCommand(Intent intent, int flags, int startId) { setUpLocationClientIfNeeded(); if(!mLocationClient.isConnected() || !mLocationClient.isConnecting()) mLocationClient.connect(); return START_STICKY; } 

并在onConnected方法中,我发送一个位置请求,

 @Override public void onConnected(Bundle arg0) { System.out.println("Connected ..."); mLocationClient.requestLocationUpdates(REQUEST, this); } 

REQUEST对象是,

  private static final LocationRequest REQUEST = LocationRequest.create() .setInterval(5*60*1000) // 5 minutes .setFastestInterval(3*60*1000) // 3 minutes .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY); 

现在的问题是,

  1. onLocationChanged方法不会以给定的时间间隔(即5分钟或最快的间隔3分钟)被调用。 从日志中我可以看到,它只被调用两次或三次之后,根本没有被调用(我在1小时后检查)。

我的上面的代码是什么问题? (我也看不到任何“断开连接”的日志)

  1. 为了解决这个问题,我试图用alarmmanager来定期调用这个任务。 现在,如何通过来自广播接收机的Locationclient获取单个位置更新。 (locationclient.getLastlocation()只返回最后存储的位置,但它没有请求一个新的位置)

后台服务的完整源代码可在此处获得:

https://gist.github.com/blackcj/20efe2ac885c7297a676

尝试添加超级调用onStartCommand。

 /** * Keeps the service running even after the app is closed. * */ public int onStartCommand (Intent intent, int flags, int startId) { super.onStartCommand(intent, flags, startId); setUpLocationClientIfNeeded(); if(!mLocationClient.isConnected() || !mLocationClient.isConnecting()) { mLocationClient.connect(); } return START_STICKY; }