Enviar ubicación actual al servidor periódicamente en android

Tengo que enviar los detalles de mi ubicación actual (lat & long) al servidor periódicamente (Ej: por cada 5 minutos). ¿Hay alguna mejor manera? Sé cómo obtener la ubicación actual y cómo enviar los detalles al servidor. Pero ¿cómo puedo repetir esto en intervalos periódicos?

Registre una alarma usando AlarmManager para despertar después de 5min cuando el usuario abra la aplicación por primera vez. Crear un servicio (buscar ubicación y actualizar al servidor) para que se ejecute cuando la alarma notifique su aplicación. Después de que el servicio terminó el trabajo, registre para una alarma otra vez para despertar después de 5min. De esta manera usted puede lograr su tarea.

árbitro

Android: cómo enviar periódicamente la ubicación a un servidor

http://developer.android.com/reference/android/app/AlarmManager.html

http://developer.android.com/reference/android/app/Service.html

1ª Edición – Añadir muestra de código

Paso 1 – Crear administrador de alarmas y registrar la alarma

 AlarmManager alarmMgr = (AlarmManager) getSystemService(Context.ALARM_SERVICE); Intent intent = new Intent(Main.this, YourWakefulReceiver.class); bool flag = (PendingIntent.getBroadcast(Main.this, 0, intent, PendingIntent.FLAG_NO_CREATE)==null); /*Register alarm if not registered already*/ if(flag){ PendingIntent alarmIntent = PendingIntent.getBroadcast(Main.this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT); // Create Calendar obj called calendar /* Setting alarm for every one hour from the current time.*/ int intervalTimeMillis = 1000 * 60 * 60; // 1 hour alarmMgr.setRepeating(AlarmManager.RTC_WAKEUP, calander.getTimeInMillis(), intervalTimeMillis, alarmIntent); } 

Paso 2 – Crear una clase de receptor

 public class YourWakefulReceiver extends WakefulBroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { Intent service = new Intent(context, SimpleWakefulService.class); startWakefulService(context, service); } } } 

Setp 3 – Crear clase de servicio

 public class YourService extends IntentService { private static String tagName = "YourService"; public SimpleWakefulService() { super("YourService"); } @Override protected void onHandleIntent(Intent intent) { // Start your location LocationUtil.startLocationListener(); try { // Wait for 10 seconds Thread.sleep(1000*10); } catch (InterruptedException e) { } //Stop location listener LocationUtil.stopLocationListener(); // upload or save location uploadGps(); SimpleWakefulReceiver.completeWakefulIntent(intent); } } 

Paso 4 – Registrar servicio y receptor

 <service android:name="com.envision.ghari.services.YourService"></service> <receiver android:name="com.envision.ghari.receivers.YourWakefulReceiver"></receiver> 

Nota: Este código es para entender la implementación. No compilará.

Uso de BroadcasteReceiver

Es una buena opción para enviar peticiones periódicas …

Aquí hay un tutorial para usar BroadcasteReceiver

La mejor manera de despertar el servicio usando el AlarmManager y publicar la ubicación que llegue al servidor.

Como no requiere interacción UI debe crear un servicio para ello, el servicio invocará el método requestLocationUpdates, en este método, pasará el tiempo mínimo del parámetro a 5 minutos.

Estoy desarrollando una aplicación que obtiene la posición del teléfono celular durante todo el día en 10 y 15 segundos en un servicio, funciona bien, pero a veces el método OnLocationChanged de la Red de escuchas de los proveedores para ser llamado.

  import android.location.Address; import android.location.Geocoder; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.AdapterView; import android.widget.ListView; import android.widget.SimpleCursorAdapter; import android.widget.TextView; import java.io.IOException; import java.util.List; import foodinn.databases.LocationUpdaterDatabase; public class LocationUpdatesActivity extends AppCompatActivity { private LocationUpdaterDatabase locationUpdaterDatabase; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_location_updates); locationUpdaterDatabase = new LocationUpdaterDatabase(this, "Locations.db", null, 1); final Geocoder geocoder = new Geocoder(this); ListView listView = (ListView) findViewById(R.id.locationUpdatesListView); listView.setAdapter(new SimpleCursorAdapter(this, R.layout.location_updates_list_view_view, locationUpdaterDatabase.getLocationUpdates(), new String[] {"latitude", "longitude", "whenUpdated"}, new int[] {R.id.listViewTextView1, R.id.listViewTextView2, R.id.listViewTextView3}, SimpleCursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER)); listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) { double latitude = Double.valueOf(((TextView) view.findViewById(R.id.listViewTextView1)).getText().toString()); double longitude = Double.valueOf(((TextView) view.findViewById(R.id.listViewTextView2)).getText().toString()); try { List<Address> addressList = geocoder.getFromLocation(latitude, longitude, 1); String address = addressList.get(0).getAddressLine(0); // If any additional address line present than only, check with max available address lines by getMaxAddressLineIndex() String city = addressList.get(0).getLocality(); String state = addressList.get(0).getAdminArea(); String country = addressList.get(0).getCountryName(); String postalCode = addressList.get(0).getPostalCode(); String knownName = addressList.get(0).getFeatureName(); ((TextView) view.findViewById(R.id.listViewTextView4)).setText(address + ", " + city + ", " + country); } catch (IOException e) { e.printStackTrace(); } } }); } } 
  • Obtener la dirección de ubicación actual de la aplicación de Android
  • AddProximityAlert no funciona (no hace requestLocationUpdates) - Android
  • Tiempo de sincronización para la grabación de datos en varios dispositivos Android
  • Trabajar con GPS vía libhardware en Android
  • Ubicación de Android GPS periódicamente
  • Comprobación del estado del GPS con Google Play Services
  • ¿Cuáles son los criterios de mayor exactitud: ACCURACY_HIGH o ACCURACY_FINE?
  • Cliente de la API de Google que no se conecta de nuevo después de onConnectionSuspended (int Cause) called
  • Permisos de tiempo de ejecución de Android en las versiones de android debajo de M?
  • Realidad Aumentada - Utilizando sólo GPS
  • LocationClient getLastLocation () devolver null
  • FlipAndroid es un fan de Google para Android, Todo sobre Android Phones, Android Wear, Android Dev y Aplicaciones para Android Aplicaciones.