GPSTracker Class not working

4.2k views Asked by At

I have tried to use a GPSTracker class that I found online in my application, and I had it working earlier, but it seems to now inexplicably not work.

public class GPSTracker extends Service implements LocationListener {

private static final String TAG = "GPSTracker";
private final Context mContext;

// flag for GPS status
boolean isGPSEnabled = false;

// flag for network status
boolean isNetworkEnabled = false;

// flag for GPS status
boolean canGetLocation = false;

Location location = null; // location
double latitude; // latitude
double longitude; // longitude

// The minimum distance to change Updates in meters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters

// The minimum time between updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = 1000 * 30 * 1; //

// Declaring a Location Manager
protected LocationManager locationManager;
TextView tv;


public GPSTracker(Context c){
    this.mContext = c;
    getLocation();
}

public Location getLocation() {
    try {
        locationManager = (LocationManager) mContext.getSystemService(LOCATION_SERVICE);

        // getting GPS status
        isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);

        // getting network status
        isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);

        if (!isGPSEnabled && !isNetworkEnabled) {

        } else {
            this.canGetLocation = true;
            if (isNetworkEnabled) {
                locationManager.requestLocationUpdates(
                        LocationManager.NETWORK_PROVIDER,
                        MIN_TIME_BW_UPDATES,
                        MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                Log.d("Network", "Network Enabled");
                if (locationManager != null) {
                    location = locationManager
                            .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                    if (location != null) {
                        latitude = location.getLatitude();
                        longitude = location.getLongitude();
                    }
                }
            }
            // if GPS Enabled get lat/long using GPS Services
            if (isGPSEnabled) {
                if (location == null) {
                    locationManager.requestLocationUpdates(
                            LocationManager.GPS_PROVIDER,
                            MIN_TIME_BW_UPDATES,
                            MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                    Log.d("GPS", "GPS Enabled");
                    if (locationManager != null) {
                        location = locationManager
                                .getLastKnownLocation(LocationManager.GPS_PROVIDER);
                        if (location != null) {
                            latitude = location.getLatitude();
                            longitude = location.getLongitude();
                        }
                    }
                }
            }
        }

    } catch (Exception e) {
        e.printStackTrace();
    }

    return location;
}

/**
 * Stop using GPS listener Calling this function will stop using GPS in your
 * app
 * */
public void stopUsingGPS() {
    if (locationManager != null) {
        locationManager.removeUpdates(GPSTracker.this);
    }
}

/**
 * Function to get latitude
 * */
public double getLatitude() {
    if (location != null) {
        latitude = location.getLatitude();
    }

    // return latitude
    return latitude;
}

/**
 * Function to get longitude
 * */
public double getLongitude() {
    if (location != null) {
        longitude = location.getLongitude();
    }

    // return longitude
    return longitude;
}

 public boolean canGetLocation() {
    return this.canGetLocation;
}

In my MainActivity, I initialized a GPSTracker gps variable, and created a new instance in my onCreate() method:

gps = new GPSTracker(MapActivity.this);

Now the code that utilized this is:

@Override
public void onMapReady(GoogleMap googleMap) {
    LatLng point = new LatLng(gps.getLatitude(),gps.getLongitude());
    pointList.add(point);
    googleMap.addMarker(new MarkerOptions().position(point).title("Home"));

}

Unfortunately, my marker continually appears at (0,0), despite having Wi-Fi and GPS enabled on my phone. The only thing I can think of that has changed is battery, but I would think that it would be unaffected at a level >20%. Using Toasts shows that isGPSEnabled comes up as true, while isNetworkEnabled comes up false(not sure why that is the case either, as Wi-Fi is working fine).

I have a few related questions to try to help me understand the whole mechanism as well. When the locationManager.requestLocationUpdates() is called, do these updates continue to occur in the background? For example, when I created an instance of the GPSTracker class in the MapActivity, do I need to make another instance of the class each time I want to get my current location? Will the values of latitude and longitude change in the instance of the object held in the variable 'gps'? If that were the case I could call gps.getLatitude() every time I moved 10 meters and it would change the values of latitude and longitude automatically. Or, since GPSTracker implements LocationListener, do I need to add code in the onLocationChanged() method to request an update in location? I'm just a bit confused on the whole situation, so any help would be greatly appreciated. Thanks.

1

There are 1 answers

0
momo On BEST ANSWER

First of all you don't really start a Android Service just by creating a new instance! Android Services can be started either by calling startService() or bindService(). Also don't forget to finish the Service by calling stopSelf() (or unbindService()) after the work is done. I recommend to implement the interfaces GoogleApiClient.ConnectionCallbacks and GoogleApiClient.OnConnectionFailedListener in combination with the new FusedLocationProviderApi.

This should help you:

LocationService.java

    import android.app.Service;
    import android.content.Context;
    import android.content.Intent;
    import android.location.Location;
    import android.net.ConnectivityManager;
    import android.net.NetworkInfo;
    import android.os.Bundle;
    import android.os.IBinder;
    import android.util.Log;

    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.location.LocationListener;
    import com.google.android.gms.location.LocationRequest;
    import com.google.android.gms.location.LocationServices;

    /**
     * Created by momo on 11.06.2015.
     */
    public class LocationService extends Service implements
            GoogleApiClient.ConnectionCallbacks,
            GoogleApiClient.OnConnectionFailedListener,
            LocationListener {

    private GoogleApiClient mGoogleApiClient;
    private final String TAG = LocationService.class.getSimpleName();

    private Intent intent;

    public LocationService() {
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Log.d(TAG, "onCreate()");
        mGoogleApiClient = new GoogleApiClient.Builder(this) // com.google.android.gms.location.LocationServices
                .addApi(LocationServices.API)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .build();
    }

    @Override
    public IBinder onBind(Intent intent) {
        throw new UnsupportedOperationException("Not yet implemented");
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.d(TAG, "onStartCommand() " + intent);
        this.intent = intent;

        /**
         * com.google.android.gms.common.GooglePlayServicesUtil
         */
        int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
        if (resultCode == ConnectionResult.SUCCESS) {
            Log.d(TAG, "handleActionGPS(): Connect to GooglePlayServices");
            mGoogleApiClient.connect();
        } else {
            Log.e(TAG, "GooglePlayService is not available");
            stopSelf();
        }

        return (START_REDELIVER_INTENT);
    }

    /**
     * com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks
     */
    @Override
    public void onConnected(Bundle bundle) {
        Log.d(TAG, "onConnected: Connected");
        LocationRequest mLocationRequest = LocationRequest.create();
        mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
        mLocationRequest.setInterval(10000); // nterval 10 seconds
        mLocationRequest.setNumUpdates(1); // number of location updates
        LocationServices.FusedLocationApi.requestLocationUpdates(
                mGoogleApiClient, mLocationRequest, this);
    }

    // com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks
    @Override
    public void onConnectionSuspended(int i) 
    {
        Log.i(TAG, "GoogleApiClient connection has been suspend");
        stopSelf();
    }

    /**
     * com.google.android.gms.location.LocationListener
     *
     */
    @Override
    public void onLocationChanged(Location location) {
        Log.d(TAG, "onLocationChanged()");

        LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
        mGoogleApiClient.disconnect();

        stopSelf();
    }


    // com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener
    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {
        Log.e(TAG, "GoogleApiClient connection has failed: " + connectionResult.getErrorCode());
        stopSelf();
    }

    boolean isOnline() {
        ConnectivityManager cm = (ConnectivityManager) this.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo netInfo = cm.getActiveNetworkInfo();
        return netInfo != null && netInfo.isConnectedOrConnecting();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.d(TAG, "onDestroy()");
    }

}

build.gradle

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.google.android.gms:play-services:7.5.0'
    //...
}