我打算从一个通用类的活动中获得纬度经度。
GPSResource gpsResource = new GPSResource(getApplicationContext());
double lat = gpsResource.getLatitude();
这总是返回 null。我应该如何修改代码,以便它等待 onConnected() 被调用,然后将值返回给引用的活动?
这是我的通用类代码:
public class GPSResource implements GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,LocationSource.OnLocationChangedListener,LocationListener
{
private Location location; // location
private double latitude; // latitude
private double longitude; // longitude
private GoogleApiClient mGAC;
private Context mContext;
public static final String TAG = "GPSresource";
private LocationRequest mLocationRequest;
public GPSResource(Context c)
{
mContext = c;
try
{
buildGoogleApiClient();
}
catch(Exception e)
{
Log.d(TAG,e.toString());
}
}
protected synchronized void buildGoogleApiClient()
{
mGAC = new GoogleApiClient.Builder(mContext)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
mLocationRequest = LocationRequest.create()
.setPriority(LocationRequest.PRIORITY_LOW_POWER)
.setInterval(10 * 1000) // 10 seconds, in milliseconds
.setFastestInterval(1 * 1000); // 1 second, in milliseconds
mGAC.connect();
}
public double getLatitude(){
return latitude;
}
/**
* Function to get longitude
* */
public double getLongitude() {
if (location != null) {
longitude = location.getLongitude();
}
// return longitude
return longitude;
}
@Override
public void onConnected(Bundle bundle) {
Location currentLocation = LocationServices.FusedLocationApi.getLastLocation(mGAC);
if (currentLocation == null)
{
LocationServices.FusedLocationApi.requestLocationUpdates(mGAC, mLocationRequest, this);
}
latitude = currentLocation.getLatitude();
longitude = currentLocation.getLongitude();
}
@Override
public void onConnectionSuspended(int i) {
}
@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
}
private boolean checkLocServices()
{
LocationManager manager = null;
boolean isAvailable = false;
try
{
manager = (LocationManager)mContext.getSystemService(mContext.LOCATION_SERVICE);
if (manager.isProviderEnabled(LocationManager.GPS_PROVIDER)||manager.isProviderEnabled(LocationManager.NETWORK_PROVIDER))
{
isAvailable = true;
}
else
{
isAvailable = false;
}
} catch (Exception e) {
e.printStackTrace();
}
return isAvailable;
}
@Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
if(location!=null)
{
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}