1

我正在尝试通过融合位置 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()和结果。

我该如何克服这个问题?

4

2 回答 2

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)该位置才会可用。

方法一

返回一个Location对象而不是原语。这样,如果查询得太早,您可以返回 null 并且调用者可以处理它。

方法二

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);
于 2015-09-08T10:49:22.120 回答
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);
        }
    };
于 2017-05-26T01:43:42.100 回答