como enviar la direccion y coordenadas del gps a una base de datos de forma automatica en android studio

Hola comunidad, espero que se encuentres bien. Hoy veremos un tutorial muy interesante revise mi bandeja y había 10 peticiones sobre el mismo tema, de como enviar la dirección y coordenadas del gps a una base de datos de forma automática en android studio entonces déjenme contarle que hay una forma de enviar cualquier dato a nuestra base de datos por intermedio de tareas de segundo plano(Background)  y de estas hay 3 formas muy conocidas hasta el día de hoy.
1) AsyncTAsk
2) Thread
3) Handler
No voy entrar en detalle porque alargaríamos el tutorial te vas aburrir y como yo se que eres Don o Doña vergas e iras de frente por el código:
Para este ejercicio utilizaremos Handler . Aclaremos que ya hemos trabajado con ejercicios de como obtener la dirección y las coordenadas del gps si aun no lo has visto te dejo los enlaces:

Bien entonces tomaremos el ultimo link como ejemplo así que te recomiendo que vallas a ese enlace lo mires por un rato luego regreses y nos pongamos manos a la obra, si ya miraste el ejercicio veras que para enviar una coordenada nueva a nuestra base de datos hay que darle clic en el botón y nosotros no queremos eso, lo que nosotros queremos es sin darle clic en ningún lado al momento de correr la aplicación se envié de forma automática la dirección en x minutos o según nuestra configuración.
Paso 1) debemos declarar nuestra clase Handler de la siguiente forma
Handler handler = new Handler();
Esto ira debajo del ya conocido 
public class MainActivity extends AppCompatActivity   {
Y debajo de este mismo código ira:

handler.post(sendData);
Quedando de la siguiente forma:

public class MainActivity extends AppCompatActivity   {
TextView mensaje1;
TextView mensaje2;
Handler handler = new Handler();
@Override protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
handler.post(sendData);

mensaje1 = (TextView) findViewById(R.id.mensaje_id);
mensaje2 = (TextView) findViewById(R.id.mensaje_id2);
Ahora viene la parte mas interesante, nosotros antes para enviar nuestra dirección lo hacíamos por medio del onclick llamando a nuestro método insertar el cual a su vez enviaba nuestra dirección a la webservices y era de la siguiente forma:

botonGuardar.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
new Insertar(MainActivity.this).execute();
}
});

Entonces ahora debemos borrar el onclick y enviar el método new Insertar(MainActivity.this).execute(); por medio de nuestro Handler y el código seria algo así:

protected void onDestroy() {
super.onDestroy();
handler.removeCallbacks(sendData);
}
private final Runnable sendData = new Runnable(){
public void run(){
try {
new Insertar(MainActivity.this).execute();
handler.postDelayed(this, 1000);
}
catch (Exception e) {
e.printStackTrace();
}
}
};

Y como gestionamos cada cuantos segundos, minutos u horas se enviara la dirección a nuestra BD, pues esta parte del código lo gestiona:

handler.postDelayed(this, 1000);

1000  = 1 segundo
2000  = 2 segundos
60000= 60 segundos

Y asi sucesivamente con eso ya estaria completa nuestra aplicacion a continuacion les dejo el codigo completo y armado:

public class MainActivity extends AppCompatActivity   {
TextView mensaje1;
TextView mensaje2;
Handler handler = new Handler();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
handler.post(sendData);

mensaje1 = (TextView) findViewById(R.id.mensaje_id);
mensaje2 = (TextView) findViewById(R.id.mensaje_id2);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION,}, 1000);
} else {
locationStart();
}
}
//Enviamos de forma automatica la direcion
@Override
protected void onDestroy() {
super.onDestroy();
handler.removeCallbacks(sendData);
}
private final Runnable sendData = new Runnable(){
public void run(){
try {
new Insertar(MainActivity.this).execute();


handler.postDelayed(this, 1000);
}
catch (Exception e) {
e.printStackTrace();
}
}
};
//Insertamos los datos a nuestra webService
private boolean insertar(){
HttpClient httpClient;
List<NameValuePair> nameValuePairs;
HttpPost httpPost;
httpClient = new DefaultHttpClient();
httpPost = new HttpPost("http://192.168.8.118/gpsbd/insertar.php");//url del servidor
//empezamos añadir nuestros datos
nameValuePairs = new ArrayList<NameValuePair>(4);
nameValuePairs.add(new BasicNameValuePair("coordenadas",mensaje1.getText().toString().trim()));
nameValuePairs.add(new BasicNameValuePair("direccion",mensaje2.getText().toString().trim()));

try {
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
httpClient.execute(httpPost);
return true;


} catch(UnsupportedEncodingException e){
e.printStackTrace();
}catch (ClientProtocolException e){
e.printStackTrace();

}catch (IOException e){
e.printStackTrace();
}
return false;
}
//AsyncTask para insertar Datos
class Insertar extends AsyncTask<String,String,String> {

private Activity context;

Insertar(Activity context){
this.context=context;
}

protected String doInBackground(String... params) {
// TODO Auto-generated method stub
if(insertar())
context.runOnUiThread(new Runnable(){
@Override
public void run() {
// TODO Auto-generated method stub
Toast.makeText(context, "Datos insertado con éxito", Toast.LENGTH_LONG).show();
mensaje1.setText("");
mensaje2.setText("");

}
});
else
context.runOnUiThread(new Runnable(){
@Override
public void run() {
// TODO Auto-generated method stub
Toast.makeText(context, "Datos no insertado con éxito", Toast.LENGTH_LONG).show();
}
});
return null;
}
}

//Apartir de aqui empezamos a obtener la direciones y coordenadas
private void locationStart() {
LocationManager mlocManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Localizacion Local = new Localizacion();
Local.setMainActivity(this);
final boolean gpsEnabled = mlocManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
if (!gpsEnabled) {
Intent settingsIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(settingsIntent);
}
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION,}, 1000);
return;
}
mlocManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, (LocationListener) Local);
mlocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, (LocationListener) Local);

mensaje1.setText("Localizacion agregada");
mensaje2.setText("");
}

public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
if (requestCode == 1000) {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
locationStart();
return;
}
}
}

public void setLocation(Location loc) {
//Obtener la direccion de la calle a partir de la latitud y la longitud
if (loc.getLatitude() != 0.0 && loc.getLongitude() != 0.0) {
try {
Geocoder geocoder = new Geocoder(this, Locale.getDefault());
List<Address> list = geocoder.getFromLocation(
loc.getLatitude(), loc.getLongitude(), 1);
if (!list.isEmpty()) {
Address DirCalle = list.get(0);
mensaje2.setText(DirCalle.getAddressLine(0));
}

} catch (IOException e) {
e.printStackTrace();
}
}
}
/* Aqui empieza la Clase Localizacion */
public class Localizacion implements LocationListener {
MainActivity mainActivity;

public MainActivity getMainActivity() {
return mainActivity;
}

public void setMainActivity(MainActivity mainActivity) {
this.mainActivity = mainActivity;
}

@Override
public void onLocationChanged(Location loc) {
// Este metodo se ejecuta cada vez que el GPS recibe nuevas coordenadas
// debido a la deteccion de un cambio de ubicacion

loc.getLatitude();
loc.getLongitude();

String Text = "Lat = "+ loc.getLatitude() + "n Long = " + loc.getLongitude();
mensaje1.setText(Text);
this.mainActivity.setLocation(loc);
}

@Override
public void onProviderDisabled(String provider) {
// Este metodo se ejecuta cuando el GPS es desactivado
mensaje1.setText("GPS Desactivado");
}

@Override
public void onProviderEnabled(String provider) {
// Este metodo se ejecuta cuando el GPS es activado
mensaje1.setText("GPS Activado");
}

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

Recuerden aquí solo se ha cambiado el MainActivity.java la web services y lo demás lo pueden sacar de aquí :

Si tienen preguntas o dudas sobre que tipo de background es mejor les reocmiendo que vean este post: Thread, Handler y AsyncTask ¿cuál elegir?

Deja una respuesta

Tu dirección de correo electrónico no será publicada.

WhatsApp chat