IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

Android Discussion :

Récupérer valeur fonction localisation d'un service dans une Activity


Sujet :

Android

Vue hybride

Message précédent Message précédent   Message suivant Message suivant
  1. #1
    Membre très actif
    Homme Profil pro
    Développeur Logiciel
    Inscrit en
    Décembre 2015
    Messages
    230
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Sarthe (Pays de la Loire)

    Informations professionnelles :
    Activité : Développeur Logiciel
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Décembre 2015
    Messages : 230
    Par défaut Récupérer valeur fonction localisation d'un service dans une Activity
    Bonjour à tous,

    J'ai une question concernant la récupération de donnée sous Android particulière.
    J'avais crée à un moment une classe service "GPS_Service" qui sert à crée ou retourner la Latitude et la Longitude du GPS de l'utilisateur.
    Sauf que maintenant je voudrais récupérer ses coordonnées dans une Activity (une Map Activity) mais je ne sais pas trop comment m'y prendre pour que cela fonctionne correctement.

    Voilà le code de mon Service:

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
     
    import android.app.Service;
    import android.content.Context;
    import android.content.Intent;
    import android.location.Location;
    import android.location.LocationManager;
    import android.os.Bundle;
    import android.os.IBinder;
    import android.provider.Settings;
    import android.support.annotation.Nullable;
     
    //import com.google.android.gms.location.LocationListener;
    import android.location.LocationListener;
     
     
    public class GPS_Service extends Service {
     
        private LocationListener listener;
        private LocationManager locationManager;
        //private LocationListener locationListener;
     
        @Nullable
        @Override
        public IBinder onBind(Intent intent) {
            return null;
        }
     
        public void onCreate() {
            locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
            listener = new LocationListener() {
                boolean gpsEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
     
                //function qui renvoie la latitude et la longitude de notre position sous forme de text
                @Override
                public void onLocationChanged(Location location) {
                    Intent localisation = new Intent("location_update");
                    localisation.putExtra("coordinates", location.getLongitude() + " " + location.getLatitude());
                    //On envoie notre intent grâce à la fonction "sendBroadcast"
                    sendBroadcast(localisation);
                }
     
                //@Override
                public void onStatusChanged(String s, int i, Bundle extras) {
     
                }
     
                //@Override
                public void onProviderEnabled(String s) {
     
                }
     
                //@Override
                public void onProviderDisabled(String s) {
                    Intent localisation = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                    localisation.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    startActivity(localisation);
                }
     
                /**
                 * //On envoie nos coordonnées Longitude et Latitude à notre map
                Intent IntentLocalisation = new Intent("location_update");
                IntentLocalisation.putExtra("coordonnées :", listener.onLocationChanged().getLongitude() + " " + listener.onLocationChanged().getLatitude());
                //On envoie notre intent grâce à la fonction "sendBroadcast"
                sendBroadcast(IntentLocalisation);**/
     
     
     
            };
     
            /**
            //On envoie nos coordonnées Longitude et Latitude à notre map
            Intent IntentLocalisation = new Intent("location_update");
            IntentLocalisation.putExtra("coordonnées :", listener.onLocationChanged().getLongitude() + " " + listener.onLocationChanged().getLatitude());
            //On envoie notre intent grâce à la fonction "sendBroadcast"
            sendBroadcast(IntentLocalisation);**/
     
            locationManager = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
     
            //noinspection MissingPermission
            locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,3000,0,listener);
        }
     
     
        @Override
        public void onDestroy() {
            super.onDestroy();
            if(locationManager != null){
                //noinspection MissingPermission
                locationManager.removeUpdates(listener);
            }
        }
     
    }
    J'ai une petite erreur au niveau de mes paranthèses également, donc faute syntaxique probablement
    Nom : erreur android.png
Affichages : 253
Taille : 13,8 Ko

    J'avais essayé avec un Intent mais ce n'est peut-être pas la solution.

    Je veux retourner la position de mon utilisateur dans mon code ici:

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
     
    public void onMapReady(GoogleMap googleMap) {
            mMap = googleMap;
            //mMap.append()
     
     
            // Add a marker in Sydney and move the camera
            LatLng sydney = new LatLng(-34, 151);
            //Afficher la position de l'utilisateur
            float UserLatitude = GPS_Service.listener.onLocationChanged();
            float UserLongitude = ;
            LatLng maPosition = new LatLng(GPS_Service.listener.location.getLongitude(), GPS_Service.listener.location.getLatitude());
            mMap.addMarker(new MarkerOptions().position(sydney).title("Votre position"));
            mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
        }
    Après que ma map soit crée.
    Si quelqu'un à une idée qui pourrait m'éclairer merci d'avance.

  2. #2
    Membre très actif
    Homme Profil pro
    Développeur Logiciel
    Inscrit en
    Décembre 2015
    Messages
    230
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Sarthe (Pays de la Loire)

    Informations professionnelles :
    Activité : Développeur Logiciel
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Décembre 2015
    Messages : 230
    Par défaut
    J'ai ça:

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
     
     
        public void onLocationChanged(final Location location) {
            //On affiche dans un Toat la nouvelle Localisation
            final StringBuilder msg = new StringBuilder("lat : ");
            msg.append(location.getLatitude());
            msg.append( "; lng : ");
            msg.append(location.getLongitude());
     
            Toast.makeText(this, msg.toString(), Toast.LENGTH_SHORT).show();
     
            //Mise à jour des coordonnées
            final LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
            //gMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 15));
     
     
        }
     
     
        public void onMapReady(GoogleMap googleMap) {
            mMap = googleMap;
            //mMap.append()
     
            LatLng sydney = new LatLng(-34, 151);
     
            mMap.addMarker(new MarkerOptions().position(sydney).title("Votre position"));
            mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
     
            mMap.addMarker(new MarkerOptions().position(onLocationChanged(Location).latLng).title("Votre position"));
            mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
     
     
        }
    Et je voudrais récupérer la function "onLocationChanged" mais pas possible.
    Pour afficher la position de l'utilisateur et l'update à chaque fois sur la map.

  3. #3
    Membre très actif Avatar de jmonga
    Homme Profil pro
    Développeur Java
    Inscrit en
    Novembre 2014
    Messages
    175
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 29
    Localisation : Congo-Kinshasa

    Informations professionnelles :
    Activité : Développeur Java
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Novembre 2014
    Messages : 175
    Par défaut
    Selon moi comme tu as des problèmes de communication entre ton service et ton activité et que les intents posent problème.

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
     
           //ajoute ceci dans la classe de ton service
           public interface IEnvoiCoordonne{
                  public void envoi(Location location);
           }
     
     
           // Déclare une variable avec comme type la classe de ton Activité qui affiche la map
           // Et dans la méthode de ton récepteur de localisation c'est à dire LocationListener.
           public void onLocationChanged(Location location) {
                  variableActiviteMap.envoi(location) ;
            }
     
           // implémente cette interface dans ton activité qui affiche la map
           public class Activité implémente GPS_Service.IEnvoiCoordonne {
     
           @override
            public void envoi (Location location) {
                    float latitude = location. getLatitude();
                    float longitude = location. getLongitude();
            }
    }
    Remarque :
    - les deux variable longitude et latitude doivent être globales pour te permettre de les utilisées dans les méthodes de ta map.

    pour faire ce que je fais il même des bibliothèques qui peuvent t'aider c'est par exemple Oto ou eventBus

  4. #4
    Membre très actif
    Homme Profil pro
    Développeur Logiciel
    Inscrit en
    Décembre 2015
    Messages
    230
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Sarthe (Pays de la Loire)

    Informations professionnelles :
    Activité : Développeur Logiciel
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Décembre 2015
    Messages : 230
    Par défaut
    Merci je regarde ça.

  5. #5
    Membre très actif
    Homme Profil pro
    Développeur Logiciel
    Inscrit en
    Décembre 2015
    Messages
    230
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Sarthe (Pays de la Loire)

    Informations professionnelles :
    Activité : Développeur Logiciel
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Décembre 2015
    Messages : 230
    Par défaut
    Le problème c'est que si j'essaye de réutiliser les variables "latitude" ou longitude" de la méthode envoie ça ne fonctionne pas.
    La méthode envoie n'est pas utilisé.

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
     
            //LatLng maPosition = new LatLng(latitude, longitude);
            LatLng maPosition = new LatLng(envoi(Location).latitude, envoi(Location).longitude);
    Contrairement à celui du dessus ça ne fonctionne pas, mais celui du dessus va chercher la variable globale qui ne va rien faire

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
     
        private double latitude;
        private double longitude;
    Je l'ai ai mis en double puisqu'il attend un double et non un float.

    Et je ne peux pas implémenter "GPS_Service.IEnvoiCoordonne" dans mon Activity.

  6. #6
    Membre très actif
    Homme Profil pro
    Développeur Logiciel
    Inscrit en
    Décembre 2015
    Messages
    230
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Sarthe (Pays de la Loire)

    Informations professionnelles :
    Activité : Développeur Logiciel
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Décembre 2015
    Messages : 230
    Par défaut
    Bon avec ça j'ai quelque chose qui s'affiche:
    (je crée ma map dans ma fonction onCreate déjà)

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
     
    public void onMapReady(GoogleMap googleMap) {
            mMap = googleMap;
            //mMap.append()
     
            //getSystemService(GPS_Service.class);
            // Add a marker in Sydney and move the camera
     
     
            //LatLng maPosition = new LatLng(latitude, longitude);
            Location location = new Location("UserPosition");
            //Location location = location;
            latitude = location.getLatitude();
            longitude = location.getLongitude();
            LatLng maPosition = new LatLng(latitude, longitude);
     
            //Afficher la position de l'utilisateur
     
            mMap.addMarker(new MarkerOptions().position(maPosition).title("Votre position"));
            mMap.moveCamera(CameraUpdateFactory.newLatLng(maPosition));
    Par contre, j'ai bien l'impression que mes valeurs latitude et longitude sont est reste à 0..

Discussions similaires

  1. Réponses: 3
    Dernier message: 04/11/2010, 13h03
  2. Réponses: 1
    Dernier message: 20/07/2010, 12h28
  3. Réponses: 5
    Dernier message: 01/07/2010, 18h02
  4. Réponses: 3
    Dernier message: 17/09/2008, 14h02
  5. Réponses: 2
    Dernier message: 24/08/2006, 10h46

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo