使用Google Play Service Api创建类库以获取当前位置

时间:2015-07-01 11:19:01

标签: android gps google-play-services

我正在开发获取当前位置的应用。我正在使用谷歌播放服务。 这是我的课程,以获得lat和long。

public class GetGPS extends Service implements GoogleApiClient.ConnectionCallbacks,
    GoogleApiClient.OnConnectionFailedListener {

private static final String TAG = MainActivity.class.getSimpleName();

private final static int PLAY_SERVICES_RESOLUTION_REQUEST = 1000;

private Location mLastLocation;

// Google client to interact with Google API
private GoogleApiClient mGoogleApiClient;

// boolean flag to toggle periodic location updates
private boolean mRequestingLocationUpdates = false;

private LocationRequest mLocationRequest;

// Location updates intervals in sec
private static int UPDATE_INTERVAL = 10000; // 10 sec
private static int FATEST_INTERVAL = 5000; // 5 sec
private static int DISPLACEMENT = 5; // 10 meters

private final Context mContext;

private double kinhdo=0;
private double vido=0;

public GetGPS(Context mContext) {
    this.mContext = mContext;
    if (checkPlayServices()) {
        buildGoogleApiClient();
        if(mGoogleApiClient!=null) {
            mGoogleApiClient.connect();
        }
    }
    displayLocation();
}

private void displayLocation() {

    mLastLocation = LocationServices.FusedLocationApi
            .getLastLocation(mGoogleApiClient);

    if (mLastLocation != null) {
        kinhdo = mLastLocation.getLatitude();
        vido = mLastLocation.getLongitude();
    }
}

public double getKinhdo(){
    return this.kinhdo;
}

public double getVido(){
    return this.vido;
}

/**
 * Creating google api client object
 * */
protected synchronized void buildGoogleApiClient() {
    mGoogleApiClient = new GoogleApiClient.Builder(mContext)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .addApi(LocationServices.API).build();
}

/**
 * Method to verify google play services on the device
 * */
private boolean checkPlayServices() {
    int resultCode = GooglePlayServicesUtil
            .isGooglePlayServicesAvailable(mContext);
    if (resultCode != ConnectionResult.SUCCESS) {
        Log.d("service1", "error api ");
        return false;
    }
    return true;
}



@Override
public void onConnected(Bundle bundle) {
    // Once connected with google api, get the location
    displayLocation();
}

@Override
public void onConnectionSuspended(int i) {
    mGoogleApiClient.connect();
}


@Override
public IBinder onBind(Intent intent) {
    return null;
}

@Override
public void onConnectionFailed(ConnectionResult connectionResult) {

}

现在,我使用这个类来获取当前位置:

                GetGPS gps=new GetGPS(Khachhang.this);
                Log.d("gps coor",Double.toString(gps.getKinhdo)+ ","+Double.toString(gps.getVido));

它始终显示0,0。 我无法得到我的位置。 你能帮我解决这个问题吗? 非常感谢。

0 个答案:

没有答案