Reputation: 949
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);
}
}
}
}
Upvotes: 2
Views: 1734
Reputation: 574
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
Upvotes: 0
Reputation: 2214
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..
Upvotes: 1