1

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.

captura del servicio corriendo 100%

Muchisimas gracias con antelación Saludos

1 respuesta 1

1

Lo primero que te diría es que en una parte de tu código denotas esto:

handler.postDelayed(this, 10000);//se ejecutara cada 10 segundos

Y en realidad eso no hace que se ejecute cada 10 segundos tu tarea, sino 10 segundos después y por una sola ocasión. Posteriormente, mencionas que a veces funciona, y a veces no... y lo que veo en esta parte de tu código:

LocationManager locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 100, this);

Es que indicas que te realice actualizaciones de la geolocalizacion, sí lo mas pronto posible, pero si hay diferencia de al menos 100 metros entre la ubicación actual y la nueva, y tal vez por eso no te anda ningún cambio porque supongo pruebas esa información sin moverte demasiado.. Te pongo unas líneas que denotan lo que te acabo de mencionar:

        //Minimo tiempo para updates en Milisegundos
    private static final long MIN_TIEMPO_ENTRE_UPDATES = 1000 * 60 * 1; // 1 minuto
    //Minima distancia para updates en metros.
    private static final long MIN_CAMBIO_DISTANCIA_PARA_UPDATES = 1.5; // 1.5 metros

    locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,
            MIN_TIEMPO_ENTRE_UPDATES, MIN_CAMBIO_DISTANCIA_PARA_UPDATES, locListener,
            this);

Por último, para que garantices que tus servicios siempre se ejecuten en segundo plano aunque se cierre la app, es correcto hacerlo con un Service, sin embargo yo le añadiría un ForegroundService, un ejemplo sería el siguiente:

En tu Service

    private void requestForegroundNoti(){
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
        startMyOwnForeground();
    }else{
        // Se construye la notificación (Android Viejos)
        NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
                .setSmallIcon(android.R.drawable.ic_dialog_dialer)
                .setContentTitle("MONITOR Activo")
                .setContentText("Monitoreando valores de fit band B8");
        startForeground(1, builder.build());
    }
}

private void startMyOwnForeground(){
    String NOTIFICATION_CHANNEL_ID = "com.gh.b2w.monitorIA";
    String channelName = "BLE CT Service";
    NotificationChannel chan = new NotificationChannel(NOTIFICATION_CHANNEL_ID, channelName, NotificationManager.IMPORTANCE_LOW);
    chan.setLightColor(Color.BLUE);
    chan.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);
    NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    assert manager != null;
    manager.createNotificationChannel(chan);

    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID);
    Notification notification = notificationBuilder.setOngoing(true)
            .setSmallIcon(R.drawable.ic_watch_24)
            .setColor(Color.BLUE)
            .setContentTitle("MONITOR IA Activo")
            .setContentText("Monitoreando valores de fit band B8")
            .setPriority(NotificationManager.IMPORTANCE_DEFAULT)
            .setCategory(Notification.CATEGORY_SERVICE)
            .build();
    startForeground(2, notification);
}

Y en tu manifest.xml

        <service
        android:foregroundServiceType="location"
        android:name=".Services.MonitoringKodakService"
        android:enabled="true"
        android:exported="false" />

Cabe señalar que esto te creara una notificación inmediatamente después de abandonar la app, la cual no se puede eliminar a menos que el usuario vaya al apartado de configuraciones y lo haga manualmente Intenta realizar esas modificaciones y tal vez ya funcione correctamente.

Espero te sirva!

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.