2016-04-08 3 views
2

J'essaie d'obtenir l'emplacement actuel en utilisant le GPS. Donc d'abord je vérifie que le GPS est activé ou non. Si le GPS est désactivé à ce moment-là, affichez l'alerte et redirigez l'utilisateur pour activer le GPS depuis les paramètres. Lorsque le GPS est activé, puis rediriger les paramètres vers mon application à ce moment-là dans l'activité onResume, je reçois 0,00 emplacement actuel. Comment puis-je obtenir l'emplacement actuel instantané quand activer le GPS.Android: Obtenir l'emplacement actuel dans l'activité onResume

Merci d'avance.

@Override 
    protected void onResume() { 
     super.onResume(); 
     getCurrenLocation(); 
    } 


public void getCurrenLocation() { 
     gps = new GpsTracker(GetLocation.this); 
     LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE); 
//  boolean gps_enabled = false; 
//  boolean network_enabled = false; 

     try { 
      gps_enabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER); 
     } catch (Exception ex) { 
     } 

     try { 
      network_enabled = lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER); 
     } catch (Exception ex) { 
     } 
     if (gps_enabled && network_enabled) { 

      if (gps.canGetLocation()) { 
       latitude = gps.getLatitude(); 
       longitude = gps.getLongitude(); 
       // Toast.makeText(getApplicationContext(), "Your Location is - \nLat: " + latitude + "\nLong: " + longitude, Toast.LENGTH_LONG).show(); 
       if (latitude != 0.0 && longitude != 0.0) { 
        txtLocation.setVisibility(View.VISIBLE); 
        txtLong.setVisibility(View.VISIBLE); 
        txtLat.setVisibility(View.VISIBLE); 
        txtLocation.setText("Your Location is - \nLat: " + latitude + "\nLong: " + longitude); 
        txtLong.setText(Double.toString(longitude)); 
        txtLat.setText(Double.toString(latitude)); 
       } 

       Log.d("latitude onResume:: :: :: ::", String.valueOf(latitude)); 
       Log.d("longitude onResume:: :: :: ::", String.valueOf(longitude)); 
      } 
     } else if (!gps_enabled && !network_enabled) { 
      alertDialog(); 
     } 
    } 
+1

« Comment puis-je obtenir l'emplacement actuel moment où activer le GPS » Vous ne pouvez pas. Ce n'est pas comme ça que fonctionne la technologie GPS. Vous devrez demander l'emplacement et attendre les mises à jour – Budius

+1

Ce n'est pas instantané, et vous avez besoin d'un LocationListener ou vous ne recevrez aucune mise à jour. http://developer.android.com/intl/es/reference/android/location/LocationListener.html – Enpi

Répondre

0

Essayez cette classe pour obtenir la latitude et la longitude

import android.app.AlertDialog.Builder; 
import android.app.Service; 
import android.content.Context; 
import android.content.DialogInterface; 
import android.content.Intent; 
import android.location.Location; 
import android.location.LocationListener; 
import android.location.LocationManager; 
import android.os.Bundle; 
import android.os.IBinder; 
import android.provider.Settings; 

public class GPSTracker extends Service implements LocationListener { 


private Context context; 

boolean isGPSEnabled=false; 
boolean isNetworkEnabled=false; 
boolean canGetLocation=false; 

Location location; 

double latitude; 
double longitude; 

private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES=10; 
private static final long MIN_TIME_BW_UPDATES=1000*60*1; 

protected LocationManager locationManager; 

public GPSTracker(Context context) 
    { 
this.context=context; 
getLocation(); 
    } 

    public Location getLocation() 
    { 
    try{ 
    locationManager=(LocationManager)  context.getSystemService(LOCATION_SERVICE); 
    isGPSEnabled=locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER); 
    isNetworkEnabled=locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER); 




if(!isGPSEnabled && !isNetworkEnabled) 
{ 
    showSettingsAlert(); 
} 
else{ 
    this.canGetLocation=true; 
    if(isNetworkEnabled) 
    { 
     locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this); 


    if(locationManager !=null) 
    { 
     location=locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER); 

    if(location !=null) 
    { 
     latitude=location.getLatitude(); 
     longitude=location.getLongitude(); 
    } 
    } 
    } 

    if(isGPSEnabled){ 
     if(location==null) 
     { 
      locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this); 

      if(locationManager !=null) 
      { 
       location=locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER); 

       if(location !=null) 
       { 
        latitude=location.getLatitude(); 
        longitude=location.getLongitude(); 
       } 

      } 

     } 
    } 


} 


} 
catch(Exception e) 
{ 
    e.printStackTrace(); 
} 
return location; 
} 

public void stopUsingGPS() 
    { 
    if(locationManager !=null) 
    { 
    locationManager.removeUpdates(GPSTracker.this); 
    } 
    } 

    public double getLatitude() 
{ 
    if(location!=null) 
    { 
    latitude=location.getLatitude(); 
    } 
    return latitude; 

} 


public double getLongitude() 
{ 
    if(location!=null) 
    { 
    longitude=location.getLongitude(); 
    } 
    return longitude; 

} 

public boolean canGetLocation(){ 

return this.canGetLocation; 

    } 

    public void showSettingsAlert(){ 
    Builder alertDialog=new Builder(context); 
alertDialog.setTitle("GPS Settings"); 
alertDialog.setMessage("GPS is not enabled.Do you want to go to the settings menu?"); 
alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() { 

    @Override 
    public void onClick(DialogInterface dialog, int which) { 
     Intent intent=new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS); 
     context.startActivity(intent); 
    } 
}); 

alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { 

    @Override 
    public void onClick(DialogInterface dialog, int which) { 
     dialog.cancel(); 

    } 
}); 
alertDialog.show(); 
} 


@Override 
public void onLocationChanged(Location location) { 
// TODO Auto-generated method stub 

} 

@Override 
public void onStatusChanged(String provider, int status, Bundle extras) { 
    // TODO Auto-generated method stub 

} 

@Override 
public void onProviderEnabled(String provider) { 
// TODO Auto-generated method stub 

} 

@Override 
public void onProviderDisabled(String provider) { 
// TODO Auto-generated method stub 

} 

@Override 
public IBinder onBind(Intent intent) { 
// TODO Auto-generated method stub 
return null; 
} 


} 

Et puis

GPSTracker gps; 

public void getCurrenLocation() { 
    gps = new GPSTracker(classname.this); 

    if (gps.canGetLocation) { 
     double latitude = gps.getLatitude(); 
     double longitude = gps.getLongitude(); 
       } 
} 

Hope this helps

+0

Merci, mais il est encore 0.0 quand j'appelle getCurrenLocation() à "onResume" –

+0

cela fonctionne très bien pour moi .. ..did u inclure toutes les autorisations dans le manifeste? – Benedict

+0

Ouais je ai inclus toutes les autorisations dans le manifeste –

1

Avez-vous ajouté l'autorisation à votre manifeste?

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> 

je pense qu'il est impossible d'obtenir l'emplacement immédiatement après l'activation du GPS. Le GPS doit corriger les ambiguïtés et estimer votre emplacement. Si vous avez besoin d'un emplacement immédiatement vous pouvez vous l'emplacement approximatif. Cependant, cet emplacement est beaucoup plus inexact que le GPS.

+0

Oui j'ai déjà ajouté

2

@komal Il faut toujours du temps pour obtenir l'emplacement, en fonction du fournisseur et de l'endroit. Le GPS prend le signal du satellite min 3 et utilise la trilatération, donc en fonction de la force du signal et de votre emplacement, cela peut prendre du temps. Même l'application Google Map prend jusqu'à 10 secondes pour obtenir Lat/Lng parfois. Vous devez utiliser FusedLocationProvider de services Google Play

Essayez cette démo https://github.com/googlesamples/android-play-location/tree/master/LocationUpdates

+0

Droit !! Il faut du temps pour obtenir LatLong –

+0

Pour un emplacement instantané, vous pouvez obtenir le dernier emplacement connu seulement, ou bien Exécuter un service et demander une mise à jour de l'emplacement à 10 mètres et 100 ms, mais cela drainera votre batterie. –