2

I have a service that get the location of my phone. When i turn the GPS off and turn it on again, i can't get the location anymore.

Some times it return null the latitude and longitude but GPS is on...

I have a checkbox when i check it, it begin to send to my server the latitude and longitude of my device.

Here is the code. Can someone help me to optimize my code please?

SERVICE

public class LocalizationService extends Service implements Runnable {

private static final int tempo = (30 * 1000); // 1800
private LocationManager locationManager = null;
private Thread t;

@Override
public IBinder onBind(Intent arg0) {
    // TODO Auto-generated method stub
    return null;
}

@Override
public void onCreate() {

    super.onCreate();
}

@Override
public void onStart(Intent intent, int startId) {

}

@Override
public void onDestroy() {
    super.onDestroy();
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {

    if (t == null || !t.isAlive()) {
        t = new Thread(this, "ServicoId: " + startId);
        t.start();
    }
    return Service.START_STICKY;
}

@Override
public void run() {
    // TODO Auto-generated method stub
    while (true) {
        try {
            sendLocation();
            Thread.sleep(tempo);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

public void sendLocation() {

    LatLng latlong = getLocation();

    PolifreteApplication manager = (PolifreteApplication) getApplicationContext();
    Veiculo veiculo = manager.getTransportador().getVeiculo();
    int user = manager.getTransportador().getCodigo();

    if (latlong == null) {

    } else {
        veiculo.setLatitude(latlong.latitude + "");
        veiculo.setLongitude(latlong.longitude + "");

        VeiculoDAL.SendLocationVeiculo(veiculo, user);
    }
}

public LatLng getLocation() {
    // Get the location manager
    LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    Criteria criteria = new Criteria();
    String bestProvider = locationManager.getBestProvider(criteria, false);
    Location location = locationManager.getLastKnownLocation(bestProvider);
    Double lat, lon;
    try {
        lat = location.getLatitude();
        lon = location.getLongitude();
        return new LatLng(lat, lon);
    } catch (NullPointerException e) {
        e.printStackTrace();
        return null;
    }
}

}

ACTIVITY METHOD

    public void onCheckboxClicked(View view) {

    if (WebService.conexaoOk()) {

        CheckBox cblocalizacao = (CheckBox) findViewById(R.id.checkboxlocalizacao);

        boolean checked = ((CheckBox) view).isChecked();

        locationManager = (LocationManager) this
                .getSystemService(Context.LOCATION_SERVICE);

        boolean isGPSEnabled = locationManager
                .isProviderEnabled(LocationManager.GPS_PROVIDER);

        switch (view.getId()) {
        case R.id.checkboxlocalizacao:
            if (checked && !isGPSEnabled) {
                cblocalizacao.setChecked(false);
                showSettingsAlert();
            } else if (checked && isGPSEnabled) {
                Intent i = new Intent(this, LocalizationService.class);
                this.startService(i);
            } else {
                cblocalizacao.setChecked(false);
            }
        }
    }
}
Felipe A.
  • 929
  • 3
  • 12
  • 28
  • when you turn on gps, then you can not get location directly, you can get location after some time. – Chirag Savsani May 27 '15 at 13:29
  • 1
    refer to this link, it might help you - http://stackoverflow.com/questions/30237729/how-to-get-initial-location-with-locationmanager/30237809#30237809 – Logic May 27 '15 at 13:30
  • when you restart your gps it looses his fix. It needs a while to get your location back again. Wait some time untill the gps icon on tray stop blinking – Karol Żygłowicz May 27 '15 at 13:30
  • why trying the hard way,when google provides you location example ? Which gives you the location name and pincode – m0rpheu5 May 27 '15 at 13:36
  • check this out it really helps http://stackoverflow.com/questions/1513485/how-do-i-get-the-current-gps-location-programmatically-in-android/38897436#38897436 – Syed Raza Mehdi Aug 11 '16 at 13:15

2 Answers2

1

If you want to get location from Gps, see this link, http://www.androidhive.info/2012/07/android-Gps-location-manager-tutorial/, getting location from Gps is not instantaneous, you need to implement location listener and wait the call back from the Gps provider:

locationManager.requestLocationUpdates(
                            LocationManager.GPS_PROVIDER,
                            MIN_TIME_BW_UPDATES,
                            MIN_DISTANCE_CHANGE_FOR_UPDATES, this);

or you can use network provider

locationManager.requestLocationUpdates(
                            LocationManager.NETWORK_PROVIDER,
                            MIN_TIME_BW_UPDATES,
                            MIN_DISTANCE_CHANGE_FOR_UPDATES, this);

Just visit the link, and you will find the best strategy to get the most accurate possible location..

challenger
  • 2,184
  • 1
  • 18
  • 25
  • This tutorial help me alot! Thx. – Felipe A. May 27 '15 at 14:16
  • it is so bad example ... *`public class GPSTracker extends Service` then `new GPSTracker(...)`* ... It rapes my eyes ... (like other androidhive's "tutorials") – Selvin May 27 '15 at 14:25
  • @Selvin, if its a bad example, could you post a good one? I'm new in android development, i dont know the best pratics... – Felipe A. May 28 '15 at 12:09
  • try this one :http://developer.android.com/guide/topics/location/strategies.html and this http://stackoverflow.com/questions/6181704/good-way-of-getting-the-users-location-in-android ... – challenger May 28 '15 at 13:29
0

This video from Udacity gives idea about using the location services in GoogleApiClient. Since your LocationListener tries to get location using only Network not GPS, with this code snippet: locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER) probably you are getting latitude and longitude values but with a delay. I had the same problem then I begin to use new/latest Location service API and use: GoogleApiClient. First you need to implement

GoogleApiClient.ConnectionCallbacks,
        GoogleApiClient.OnConnectionFailedListener,
        LocationListener

from you activity that want to fetch the location data.

Define

private GoogleApiClient mGoogleApiClient;

mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addApi(LocationServices.API)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .build();

If you haven't add

<uses-permission `android:name="android.permission.ACCESS_FINE_LOCATION"/>` 

to the manifest file, add that.

For further documentation : https://developers.google.com/android/reference/com/google/android/gms/common/api/GoogleApiClient

More comprehensive answer about GoogleClientApi: https://stackoverflow.com/a/33599343/2644905

Community
  • 1
  • 1
omersem
  • 564
  • 7
  • 21