我有一个服务,会在后台线程中发送位置更新。我已将清单中的服务声明为:
<service android:name="mypackage.LocationUpdater"></service>
我从OnStartComand中的活动中获取数据。但是根本没有调用OnLocationChanged。我无法从服务中的任何位置调用sendLocation()方法。
public class LocationUpdater extends Service implements ConnectionCallbacks, OnConnectionFailedListener, LocationListener {
LocationListener mLocationListener;
LocationRequest mLocationRequest;
GoogleApiClient mGoogleApiClient;
Location mLastLocation; //this object should be used to request location updates
String p = "test", d = "test";
@Override
public void onCreate() {
buildGoogleApiClient();
}
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
protected void createLocationRequest() {
LocationRequest mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(5000);
mLocationRequest.setFastestInterval(3000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
p = intent.getStringExtra("ptok");
d = intent.getStringExtra("dtok");
// We want this service to continue running until it is explicitly
// stopped, so return sticky.
return START_NOT_STICKY;
}
@Override
public void onConnected(Bundle connectionHint) {
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
mGoogleApiClient);
mLocationRequest = LocationRequest.create();
mLocationRequest.setInterval(5000);
mLocationRequest.setFastestInterval(3000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
if (mLastLocation != null) {
String latitude = String.valueOf(mLastLocation.getLatitude());
String longitude = String.valueOf(mLastLocation.getLongitude());
sendLocation(p, latitude, longitude, d);
}
}
@Override
public void onConnectionSuspended(int i) {
}
@Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
if(location != null) {
double latitude = location.getLatitude();
double longitude = location.getLongitude();
Log.i("info", "Latitude :: " + latitude);
Log.i("info", "Longitude :: " + longitude);
//sending location details
sendLocation(p, String.valueOf(latitude), String.valueOf(longitude), d);
}
}
}
我还要添加onConnected也永远不会被调用。我只看到onStartComand被调用并使用intent传递我的活动发送的值。
答案 0 :(得分:1)
文档没有描述这个,但是based on this SO accepted answer,我必须明确地调用mGoogleApiClient.connect();在我的onCreate方法中。你在onStart()中调用它;来自活动。