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);
}
}
}
}