使用FusedLocation api创建帮助器类

时间:2015-09-08 10:30:43

标签: android gps fusedlocationproviderapi

我正在尝试通过融合位置api 检索位置。我尝试构建一个帮助程序类,以便我可以在整个应用程序中使用它。

代码:

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks;
import com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;

import android.app.Activity;
import android.content.Context;
import android.location.Location;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;

public class GPSTracker2  implements ConnectionCallbacks,
        OnConnectionFailedListener,LocationListener {
    // LogCat tag
    private static final String TAG = GPSTracker2.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 = 1000; // 10 sec
    private static int FATEST_INTERVAL = 500; // 5 sec
    private static int DISPLACEMENT = 10; // 10 meters

   Context context;
// flag for GPS status
    boolean canGetLocation = true;

    double latitude,longitude;

        public GPSTracker2(Context context) {
            // TODO Auto-generated constructor stub
              // First we need to check availability of play services
            this.context=context;
             createLocationRequest();
            if (checkPlayServices()) {

                // Building the GoogleApi client
                buildGoogleApiClient();
            }

            if (mGoogleApiClient != null) {
                mGoogleApiClient.connect();
            }
            // Show location button click listener
        }





    /**
     * Method to display the location on UI
     * */
    /*private void displayLocation() {

        mLastLocation = LocationServices.FusedLocationApi
                .getLastLocation(mGoogleApiClient);

        if (mLastLocation != null) {
            double latitude = mLastLocation.getLatitude();
            double longitude = mLastLocation.getLongitude();

        } else {


        }
    }*/

        /**
         * Method to display the location on UI
         * */
        private void displayLocation() {

            mLastLocation = LocationServices.FusedLocationApi
                    .getLastLocation(mGoogleApiClient);

            if (mLastLocation != null) {
                double latitude = mLastLocation.getLatitude();
                double longitude = mLastLocation.getLongitude();

            Toast.makeText(context,latitude+" "+longitude,Toast.LENGTH_LONG).show();

            } else {


            }
        }
    /**
     * Function to get latitude
     * */
    public double getLatitude(){


         mLastLocation = LocationServices.FusedLocationApi
                    .getLastLocation(mGoogleApiClient);

            if (mLastLocation != null) {
                this.canGetLocation = true;
               double latitude = mLastLocation.getLatitude();
               System.out.println("In GetLat==>"+latitude);
               return latitude;
            }else{
                System.out.println("last known null");
                return 0.0;
            }

    }

    /**
     * Function to get longitude
     * */
    public double getLongitude(){

         mLastLocation = LocationServices.FusedLocationApi
                    .getLastLocation(mGoogleApiClient);

            if (mLastLocation != null) {
                this.canGetLocation = true;
               longitude = mLastLocation.getLongitude();
               System.out.println("In Getlong==>"+longitude);
            }
            return longitude;
    }

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

    /**
     * Method to verify google play services on the device
     * */
    private boolean checkPlayServices() {
        int resultCode = GooglePlayServicesUtil
                .isGooglePlayServicesAvailable(context);
        if (resultCode != ConnectionResult.SUCCESS) {
            if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) {
                GooglePlayServicesUtil.getErrorDialog(resultCode, (Activity) context,
                        PLAY_SERVICES_RESOLUTION_REQUEST).show();
            } else {
                Toast.makeText(context,
                        "context device is not supported.", Toast.LENGTH_LONG)
                        .show();
                //finish();
            }
            return false;
        }
        return true;
    }

    /**
     * Creating location request object
     * */
    protected void createLocationRequest() {
        mLocationRequest = new LocationRequest();
        mLocationRequest.setInterval(UPDATE_INTERVAL);
        mLocationRequest.setFastestInterval(FATEST_INTERVAL);
        mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
        mLocationRequest.setSmallestDisplacement(DISPLACEMENT);
    }

    /**
     * Starting the location updates
     * */
    protected void startLocationUpdates() {

        LocationServices.FusedLocationApi.requestLocationUpdates(
                mGoogleApiClient, mLocationRequest, this);

    }

    /**
     * Stopping location updates
     */
    protected void stopLocationUpdates() {
        LocationServices.FusedLocationApi.removeLocationUpdates(
                mGoogleApiClient, this);
    }

    /**
     * Google api callback methods
     */
    @Override
    public void onConnectionFailed(ConnectionResult result) {
        Log.i(TAG, "Connection failed: ConnectionResult.getErrorCode() = "
                + result.getErrorCode());
    }

    @Override
    public void onConnected(Bundle arg0) {

        // Once connected with google api, get the location
      //  displayLocation();
        //getLatitude();
        //getLongitude();
        displayLocation();
 System.out.println("On Connected");
        if (mRequestingLocationUpdates) {
            startLocationUpdates();
        }
    }

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

    @Override
    public void onLocationChanged(Location location) {
        // Assign the new location
        mLastLocation = location;

        Toast.makeText(context, "Location changed!",
                Toast.LENGTH_SHORT).show();
        displayLocation();
        // Displaying the new location on UI
       // displayLocation();
       // getLatitude();
     //   getLongitude();
    }

    /**
     * Function to check GPS/wifi enabled
     * @return boolean
     * */
    public boolean canGetLocation() {
        return this.canGetLocation;
    }
}

我试图将其用作:

CallingClass.java

GPSTracker2 gps=new GPSTracker2(SettingsActivity.this);
        if(gps.canGetLocation())
        {
            System.out.println("lat-->"+gps.getLatitude()+" long===>"+gps.getLongitude());
        }else{
            showSettingsAlert(true);
        }

问题: 方法 gps.getLatitude() gps.getLongitude()返回 0.0 。但是在toast消息中(在displayLocation中) );方法)纬度和经度完美无缺。

因此我调试了我的应用程序,发现在调用GpsTracker2类的构造函数后,控制权返回到调用类,并且在完成调用类的onCreate 后,GoogleApiclient正在连接。因此,它无法获取调用类的 onCreate()内的纬度和经度,从而得到结果。

我怎样才能克服这个问题?

2 个答案:

答案 0 :(得分:1)

您在拥有位置之前查询gps助手。例如,在getLatitude方法中。

public double getLatitude(){
    mLastLocation = LocationServices.FusedLocationApi
                .getLastLocation(mGoogleApiClient);

    // At first mLastKnownLocation will be null
    if (mLastLocation != null) {
        this.canGetLocation = true;
        double latitude = mLastLocation.getLatitude();
        System.out.println("In GetLat==>"+latitude);
        return latitude;
    } else {
        System.out.println("last known null");
        return 0.0; // This here is what is being returned.
    }
}

直到您的apiclient致电public void onLocationChanged(Location location),才会有位置可用。

方法1

返回Location个对象而不是基元。这样,如果过早查询并且调用者可以处理它,则可以返回null。

方法2

GPS助手的用户使用它注册回调。现在,当位置可用时,他们会收到通知。

在GPSTracker课程中

List<LocationListener> listeners = new ArrayList<>();

public void registerListener(LocationListener listener) {
    listeners.add(listener);
}

public void removeListener(LocationListener listener) {
   listeners.remove(listener);
}

@Override
public void onLocationChanged(Location location) {
    mLastLocation = location;
    for (LocationListener listener : listeners) {
        listener.onLocationChanged(location);
    }
}

GPSTracker的用户

GPSTracker gps = new GPSTracker();

LocationListener myCallback = new LocationListener() {
    @Override
    public void onLocationChanged(Location location) {
        // This code runs every time your gps gets a new location
        System.out.println("lat-->"+location.getLatitude()+" long===>"+location.getLongitude());
        doStuffWithLocation(location);
    }
};
gps.registerListener(myCallback);

// Then when you are finished
gps.removeListener(myCallback);

答案 1 :(得分:0)

我找到了课程GooglePlayServicesHelper

在活动

中使用以下代码后
    geoGPS = new GooglePlayServicesHelper(mContext, true);
    mLocationListener = new LocationListener() {
        @Override
        public void onLocationChanged(Location location) {
            latitude = location.getLatitude();
            longitude = location.getLongitude();
            Logger.debug("lat: " + latitude);
            Logger.debug("long: " + longitude);
        }
    };