使用Google Play Services LocationClient作为后台服务



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

我创建了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);
}

请求对象是,

 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小时后检查)。

我上面的代码有什么问题?(我也看不到'disconnected'的任何日志)

  1. 为了解决这个问题,我尝试使用alarmmanager来定期调用任务。现在如何通过Locationclient从广播接收器获得单个位置更新。(locationclient.getLastlocation()只返回最后存储的位置,但不请求新位置)

一个后台服务的完整源代码:

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

尝试在onStartCommand中添加super调用

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

最新更新