estoy haciendo una aplicación que me mande las coordenadas a un servidor PHP por POST, en primer lugar lo intente hacer para que se ejecutara cada x tiempo con un handler, pero no he conseguido que se ejecute en los intervalos que definí,(no se si es porque se pone en modo ahorro de energía o el GPS inactivo ...) y viendo que de esta manera no me funcionó, le he intentado usando el onLocationchange del LocationListener, pero al cerrar la aplicación muere el proceso y yo necesito que se siga ejecutando en segundo plano siempre hasta que yo pare el servicio manuelmente.
Adjunto ambos códigos.
Este es el que se ejecuta con el onlocationChange
package com.androidmorefast.pc.appguardargpsbd;
import android.Manifest;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.location.LocationProvider;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.provider.Settings;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
public class ServicesGeolocation extends Service implements LocationListener {
MainActivity mainActivity;
public MainActivity getMainActivity() {
return mainActivity;
}
public void setMainActivity(MainActivity mainActivity) {
this.mainActivity = mainActivity;
}
double latitude;
double longitude;
double speed;
String direccion;
Location location;
private Context thisContent = this;
private String url;
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
}
public void getLocation(){
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
}
LocationManager locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 1000, this);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// TODO Auto-generated method stub
ejecutar();
return Service.START_STICKY;
}
private void ejecutar() {
Handler h = new Handler(Looper.myLooper());
h.post(new Runnable() {
public void run() {
getLocation();
metodoEjecutar();
}
});
}
private void metodoEjecutar(){
//new Insertar(getApplicationContext(ServicesGeolocation.this)).execute();
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
Looper.prepare();
insertar();
Looper.loop();
}
});
thread.start();
}
@Override
public void onDestroy() {
Toast.makeText(thisContent, "Servicio Detenido", Toast.LENGTH_LONG).show();
}
@Override
public void onLocationChanged(Location location) {
location.getLatitude();
location.getLongitude();
location.getSpeed();
latitude = location.getLatitude();
longitude = location.getLongitude();
speed=location.getSpeed();
if (latitude != 0.0 && longitude != 0.0) {
try {
Geocoder geocoder = new Geocoder(this, Locale.getDefault());
List<Address> list = geocoder.getFromLocation(
latitude, longitude, 1);
if (!list.isEmpty()) {
Address DirCalle = list.get(0);
direccion=DirCalle.getAddressLine(0);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
switch (status) {
case LocationProvider.AVAILABLE:
Log.d("debug", "LocationProvider.AVAILABLE");
break;
case LocationProvider.OUT_OF_SERVICE:
Log.d("debug", "LocationProvider.OUT_OF_SERVICE");
break;
case LocationProvider.TEMPORARILY_UNAVAILABLE:
Log.d("debug", "LocationProvider.TEMPORARILY_UNAVAILABLE");
break;
}
}
@Override
public void onProviderEnabled(String provider) {
Toast.makeText(thisContent, "GPS Desactivado", Toast.LENGTH_LONG).show();
}
@Override
public void onProviderDisabled(String provider) {
Toast.makeText(thisContent, "GPS Desactivado", Toast.LENGTH_LONG).show();
}
private boolean insertar() {
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
speed=location.getSpeed();
}
if (latitude != 0.0 && longitude != 0.0) {
try {
Geocoder geocoder = new Geocoder(this, Locale.getDefault());
List<Address> list = geocoder.getFromLocation(
latitude, longitude, 1);
if (!list.isEmpty()) {
Address DirCalle = list.get(0);
direccion=DirCalle.getAddressLine(0);
}
} catch (IOException e) {
e.printStackTrace();
}
}
//Log.d("TAG", direccion);
SharedPreferences sh
= getSharedPreferences("MySharedPref",
MODE_PRIVATE);
String s1 = sh.getString("mail", "");
double kmsPorHora = speed * 3.6;
HttpClient httpClient;
List<NameValuePair> nameValuePairs;
HttpPost httpPost;
httpClient = new DefaultHttpClient();
httpPost = new HttpPost("https://gda360.gonzalezdeautomocion.com/insertar.php");//url del servidor
//empezamos añadir nuestros datos
nameValuePairs = new ArrayList<NameValuePair>(5);
nameValuePairs.add(new BasicNameValuePair("coordenadas", String.valueOf(latitude)+","+String.valueOf(longitude)));
nameValuePairs.add(new BasicNameValuePair("velocidad",String.valueOf(kmsPorHora)));
nameValuePairs.add(new BasicNameValuePair("direccion",direccion));
nameValuePairs.add(new BasicNameValuePair("email",s1));
try {
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF_8"));
httpClient.execute(httpPost);
return true;
} catch(UnsupportedEncodingException e){
e.printStackTrace();
}catch (ClientProtocolException e){
e.printStackTrace();
}catch (IOException e){
e.printStackTrace();
}
return false;
}
}
y este es el que hize para que se ejecutase cada x tiempo que tampoco me funciona del todo bien porque no siempre se ejecuta
package com.androidmorefast.pc.appguardargpsbd;
import android.Manifest;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.location.LocationProvider;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.provider.Settings;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
public class ServicesGeolocation extends Service implements LocationListener {
MainActivity mainActivity;
public MainActivity getMainActivity() {
return mainActivity;
}
public void setMainActivity(MainActivity mainActivity) {
this.mainActivity = mainActivity;
}
double latitude;
double longitude;
double speed;
String direccion;
Location location;
private Context thisContent = this;
private String url;
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
}
public void getLocation(){
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
}
LocationManager locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 100, this);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// TODO Auto-generated method stub
getLocation();
// ejecutar();
return START_STICKY;
}
private void ejecutar() {
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
getLocation();
metodoEjecutar();//llamamos nuestro metodo
handler.postDelayed(this, 10000);//se ejecutara cada 10 segundos
}
}, 5);//empezara a ejecutarse después de 5 milisegundos
}
private void metodoEjecutar() {
//new Insertar(getApplicationContext(ServicesGeolocation.this)).execute();
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
try {
// insertar();
} catch (Exception e) {
e.printStackTrace();
}
}
});
thread.start();
}
@Override
public void onDestroy() {
Toast.makeText(thisContent, "Servicio Detenido", Toast.LENGTH_LONG).show();
}
@Override
public void onLocationChanged(Location location) {
Log.d("TAG", String.valueOf(location));
location.getLatitude();
location.getLongitude();
location.getSpeed();
latitude = location.getLatitude();
longitude = location.getLongitude();
speed=location.getSpeed();
if (latitude != 0.0 && longitude != 0.0) {
try {
Geocoder geocoder = new Geocoder(this, Locale.getDefault());
List<Address> list = geocoder.getFromLocation(
latitude, longitude, 1);
if (!list.isEmpty()) {
Address DirCalle = list.get(0);
direccion=DirCalle.getAddressLine(0);
}
} catch (IOException e) {
e.printStackTrace();
}
}
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
speed=location.getSpeed();
}
if (latitude != 0.0 && longitude != 0.0) {
try {
Geocoder geocoder = new Geocoder(this, Locale.getDefault());
List<Address> list = geocoder.getFromLocation(
latitude, longitude, 1);
if (!list.isEmpty()) {
Address DirCalle = list.get(0);
direccion=DirCalle.getAddressLine(0);
}
} catch (IOException e) {
e.printStackTrace();
}
}
SharedPreferences sh
= getSharedPreferences("MySharedPref",
MODE_PRIVATE);
String s1 = sh.getString("mail", "");
double kmsPorHora = speed * 3.6;
HttpClient httpClient;
List<NameValuePair> nameValuePairs;
HttpPost httpPost;
httpClient = new DefaultHttpClient();
httpPost = new HttpPost("https://gda360.gonzalezdeautomocion.com/insertar.php");//url del servidor
//empezamos añadir nuestros datos
nameValuePairs = new ArrayList<NameValuePair>(5);
nameValuePairs.add(new BasicNameValuePair("coordenadas", String.valueOf(latitude)+","+String.valueOf(longitude)));
nameValuePairs.add(new BasicNameValuePair("velocidad",String.valueOf(kmsPorHora)));
nameValuePairs.add(new BasicNameValuePair("direccion",direccion));
nameValuePairs.add(new BasicNameValuePair("email",s1));
try {
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF_8"));
httpClient.execute(httpPost);
} catch(UnsupportedEncodingException e){
e.printStackTrace();
}catch (ClientProtocolException e){
e.printStackTrace();
}catch (IOException e){
e.printStackTrace();
}
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
switch (status) {
case LocationProvider.AVAILABLE:
Log.d("debug", "LocationProvider.AVAILABLE");
break;
case LocationProvider.OUT_OF_SERVICE:
Log.d("debug", "LocationProvider.OUT_OF_SERVICE");
break;
case LocationProvider.TEMPORARILY_UNAVAILABLE:
Log.d("debug", "LocationProvider.TEMPORARILY_UNAVAILABLE");
break;
}
}
@Override
public void onProviderEnabled(String provider) {
Toast.makeText(thisContent, "GPS Desactivado", Toast.LENGTH_LONG).show();
}
@Override
public void onProviderDisabled(String provider) {
Toast.makeText(thisContent, "GPS Desactivado", Toast.LENGTH_LONG).show();
}
}
Ninguno de los dós códigos consigo que funcione bien pero realmente el que a mi me interesa es que se ejecute cuando cambie la localización y funcione en segundo plano aun que cierre la aplicación.
Muchisimas gracias con antelación Saludos