我正在尝试获取位置更新信息。为此,我创建了一个服务,在服务类的onStartCommand中我正在创建GoogleApiClient,但我没有在服务中获得连接回调。请帮忙解决这个问题。
下面给出了服务代码和我使用startService方法启动服务的活动:
startService(new Intent(this, LocationService.class));
服务代码
public class LocationService extends Service implements GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener, LocationListener {
private GoogleApiClient mLocationClient;
private Location mCurrentLocation;
LocationRequest mLocationRequest;
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// TODO do something useful
Toast.makeText(this, "onStartCommand", Toast.LENGTH_SHORT).show();
mLocationClient = new GoogleApiClient.Builder(LocationService.this)
.addApi(LocationServices.API).addConnectionCallbacks(LocationService.this)
.addOnConnectionFailedListener(LocationService.this).build();
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(1000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mLocationRequest.setFastestInterval(1000);
return Service.START_NOT_STICKY;
}
@Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
mCurrentLocation = location;
Toast.makeText(this, mCurrentLocation.getLatitude() +", "+ mCurrentLocation.getLatitude(), Toast.LENGTH_SHORT).show();
}
@Override
public void onConnectionFailed(ConnectionResult arg0) {
// TODO Auto-generated method stub
Toast.makeText(this, "Connection failed", Toast.LENGTH_SHORT).show();
}
@Override
public void onConnected(Bundle arg0) {
// TODO Auto-generated method stub
Toast.makeText(this, "Connected", Toast.LENGTH_SHORT).show();
//if(servicesConnected()) {
LocationServices.FusedLocationApi.requestLocationUpdates(mLocationClient, mLocationRequest, this);
//}
}
@Override
public void onConnectionSuspended(int arg0) {
// TODO Auto-generated method stub
Toast.makeText(this, "Disconnected. Please re-connect.",
Toast.LENGTH_SHORT).show();
}
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
}
答案 0 :(得分:15)
主要问题:您从不致电mLocationClient.connect(),因此连接过程永远不会开始。
此外,onStartService()
可以被多次调用(即,每次调用startService()
时 - 您应该将其移至onCreate()
Service
以确保它只在您的服务生命周期内调用一次。同样,您应该onDestroy()
mLocationClient
并断开{{1}}。