2017-06-30 1 views
-1

Je reçois constamment 0,0 comme latitude et longitude du code suivant. Je ne suis pas capable de trouver l'erreur. Est-ce que quelqu'un peut m'aider s'il vous plait.Impossible d'obtenir l'emplacement à partir du GPS. Il donne toujours 0,0 comme latitude et longitude

C'est la classe que je utilise pour obtenir l'emplacement

public class GPS_tracker extends Service implements LocationListener { 

private final Context mContext; 
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 GPS_tracker(Context context) { 
    this.mContext = context; 
    getLocation(); 
} 

public Location getLocation() { 
    try { 
     locationManager = (LocationManager) mContext 
       .getSystemService(LOCATION_SERVICE); 

     isGPSEnabled = locationManager 
       .isProviderEnabled(LocationManager.GPS_PROVIDER); 

     isNetworkEnabled = locationManager 
       .isProviderEnabled(LocationManager.NETWORK_PROVIDER); 

     if (!isGPSEnabled && !isNetworkEnabled) { 
     } else { 
      this.canGetLocation = true; 

      if (isGPSEnabled) { 
       if (location == null) { 
        locationManager.requestLocationUpdates(
          LocationManager.GPS_PROVIDER, 
          MIN_TIME_BW_UPDATES, 
          MIN_DISTANCE_CHANGE_FOR_UPDATES, this); 
        Log.d("GPS Enabled", "GPS Enabled"); 
        if (locationManager != null) { 
         location = locationManager 
           .getLastKnownLocation(LocationManager.GPS_PROVIDER); 
         if (location != null) { 
          latitude = location.getLatitude(); 
          longitude = location.getLongitude(); 
         } 
        } 
       } 
      } 

      if (isNetworkEnabled) { 
       if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.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. 
        // return TODO; 
       } 
       locationManager.requestLocationUpdates(
         LocationManager.NETWORK_PROVIDER, 
         MIN_TIME_BW_UPDATES, 
         MIN_DISTANCE_CHANGE_FOR_UPDATES, this); 
       Log.d("Network", "Network"); 
       if (locationManager != null) { 
        location = locationManager 
          .getLastKnownLocation(LocationManager.NETWORK_PROVIDER); 
        if (location != null) { 
         latitude = location.getLatitude(); 
         longitude = location.getLongitude(); 
        } 
       } 
      } 

     } 

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

    return location; 
} 

public void stopUsingGPS() { 
    if (locationManager != null) { 
     if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.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. 
      // return; 
     } 
     locationManager.removeUpdates(GPS_tracker.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(){ 
    AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext); 
    alertDialog.setTitle("GPS is settings"); 
    alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?"); 
    alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() { 
     public void onClick(DialogInterface dialog,int which) { 
      Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS); 
      mContext.startActivity(intent); 
     } 
    }); 

    alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { 
     public void onClick(DialogInterface dialog, int which) { 
      dialog.cancel(); 
     } 
    }); 


    alertDialog.show(); 
} 

@Override 
public void onLocationChanged(Location location) { 
} 

@Override 
public void onProviderDisabled(String provider) { 
} 

@Override 
public void onProviderEnabled(String provider) { 
} 

@Override 
public void onStatusChanged(String provider, int status, Bundle extras) { 
} 

@Override 
public IBinder onBind(Intent arg0) { 
    return null; 
} 
} 

Ce sont les permissions que j'ai inclus dans le fichier manifeste

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

Et c'est la sur la fonction de clic que j'utilise

public void onClick(View view) { 
    if(view == btnGPS){ 
     gps=new GPS_tracker(Login.this); 
     if(gps.canGetLocation()){ 
      double latitude=gps.getLatitude(); 
      double longitute=gps.getLongitude(); 
      Toast.makeText(getApplicationContext(), "Lat:"+latitude+"Long:"+longitute, Toast.LENGTH_SHORT).show(); 
     } 
     else { 
      gps.showSettingsAlert(); 
     } 
    } 
} 
+1

avez-vous reçu des autorisations d'exécution? –

Répondre

0

Avez-vous accordé l'autorisation d'accéder à l'autorisation de localisation?

public class LocationUtil extends Service implements LocationListener { 
    private static final String TAG = LocationUtil.class.getSimpleName(); 

    public Context mContext; 

    // flag for GPS status 
    private boolean isGPSEnabled = false; 
    // flag for network status 
    private boolean isNetworkEnabled = false; 
    // flag for passive status 
    private boolean isPassiveEnabled = false; 

    private boolean canGetLocation = false; 

    private Location location; // location 
    private double latitude; // latitude 
    private double longitude; // longitude 

    // The minimum distance to change Updates in meters 
    private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 0; 
    // The minimum time between updates in milliseconds 
    private static final long MIN_TIME_BW_UPDATES = 0; 
    // Declaring a Location Manager 
    protected LocationManager locationManager; 

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

    public LocationUtil() { 
    } 

    public Location getLocation() { 
     try { 
      location = null; 
      locationManager = (LocationManager) mContext 
        .getSystemService(LOCATION_SERVICE); 

      // getting GPS status 
      isGPSEnabled = locationManager 
        .isProviderEnabled(LocationManager.GPS_PROVIDER); 

      // getting network status 
      isNetworkEnabled = locationManager 
        .isProviderEnabled(LocationManager.NETWORK_PROVIDER); 

      // getting passive status 
      isPassiveEnabled = locationManager 
        .isProviderEnabled(LocationManager.PASSIVE_PROVIDER); 

      if (!isGPSEnabled && !isNetworkEnabled && !isPassiveEnabled) { 
       showSettingsAlert(); 
      } else { 
       this.canGetLocation = true; 
       if (checkPermission()) { 
        if (isNetworkEnabled) { 
         locationManager.requestLocationUpdates(
           LocationManager.NETWORK_PROVIDER, 
           MIN_TIME_BW_UPDATES, 
           MIN_DISTANCE_CHANGE_FOR_UPDATES, this); 
         Log.d(TAG, "Network"); 
         if (locationManager != null) { 
          location = locationManager 
            .getLastKnownLocation(LocationManager.NETWORK_PROVIDER); 
          if (location != null) { 
           latitude = location.getLatitude(); 
           longitude = location.getLongitude(); 
           return location; 
          } 
         } 
        } 
        // if GPS Enabled get lat/long using GPS Services 
        if (isGPSEnabled) { 
         if (location == null) { 
          locationManager.requestLocationUpdates(
            LocationManager.GPS_PROVIDER, 
            MIN_TIME_BW_UPDATES, 
            MIN_DISTANCE_CHANGE_FOR_UPDATES, this); 
          Log.d(TAG, "GPS Enabled"); 
          if (locationManager != null) { 
           location = locationManager 
             .getLastKnownLocation(LocationManager.GPS_PROVIDER); 
           if (location != null) { 
            latitude = location.getLatitude(); 
            longitude = location.getLongitude(); 
            return location; 
           } 
          } 
         } 
        } 
        if (isPassiveEnabled) { 
         if (location == null) { 
          locationManager.requestLocationUpdates(
            LocationManager.PASSIVE_PROVIDER, 
            MIN_TIME_BW_UPDATES, 
            MIN_DISTANCE_CHANGE_FOR_UPDATES, this); 
          Log.d(TAG, "Passive Enabled"); 
          if (locationManager != null) { 
           location = locationManager 
             .getLastKnownLocation(LocationManager.PASSIVE_PROVIDER); 
           if (location != null) { 
            latitude = location.getLatitude(); 
            longitude = location.getLongitude(); 
            return location; 
           } 
          } 
         } 
        } 
       } 
      } 
     } catch (Exception e) { 
      e.printStackTrace(); 
     } 

     return location; 
    } 

    /** 
    * Stop using GPS listener 
    * Calling this function will stop using GPS in your app 
    */ 
    public void stopUsingGPS() { 
     if (locationManager != null) { 
      locationManager.removeUpdates(LocationUtil.this); 
     } 
    } 

    private boolean checkPermission() { 
     int permission = ContextCompat.checkSelfPermission(mContext, ACCESS_FINE_LOCATION); 
     if (permission == PackageManager.PERMISSION_GRANTED) { 
      return true; 
     } else { 
      return false; 
     } 
    } 

    /** 
    * Function to get latitude 
    */ 
    public double getLatitude() { 
     if (location != null) { 
      latitude = location.getLatitude(); 
     } 
     // return latitude 
     return latitude; 
    } 

    /** 
    * Function to get longitude 
    */ 
    public double getLongitude() { 
     if (location != null) { 
      longitude = location.getLongitude(); 
     } 
     // return longitude 
     return longitude; 
    } 

    /** 
    * Function to check GPS/wifi enabled 
    * 
    * @return boolean 
    */ 
    public boolean canGetLocation() { 
     return this.canGetLocation; 
    } 

    /** 
    * Function to show settings alert dialog 
    * On pressing Settings button will lauch Settings Options 
    */ 
    public void showSettingsAlert() { 
     AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext); 
     // Setting Dialog Title 
     alertDialog.setTitle("GPS is settings"); 
     // Setting Dialog Message 
     alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?"); 
     // On pressing Settings button 
     alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() { 
      public void onClick(DialogInterface dialog, int which) { 
       Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS); 
       mContext.startActivity(intent); 
      } 
     }); 
     // on pressing cancel button 
     alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { 
      public void onClick(DialogInterface dialog, int which) { 
       dialog.cancel(); 
      } 
     }); 
     // Showing Alert Message 
     alertDialog.show(); 
    } 

    @Override 
    public void onLocationChanged(Location location) { 
     getLocation(); 
    } 

    @Override 
    public void onProviderDisabled(String provider) { 
    } 

    @Override 
    public void onProviderEnabled(String provider) { 
    } 

    @Override 
    public void onStatusChanged(String provider, int status, Bundle extras) { 
     getLocation(); 
    } 


    @Override 
    public IBinder onBind(Intent arg0) { 
     return null; 
    } 
} 
+0

Oui, j'ai accordé toutes les autorisations requises. –

0

Le problème de ne pas obtenir l'emplacement en raison de la méthode de demande d'emplacement. Vous devez définir le mode de précision pour le bon emplacement. Voici mon code de fonctionnement, Essayez ceci

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback, 
     GoogleApiClient.ConnectionCallbacks, 
     GoogleApiClient.OnConnectionFailedListener, 
     LocationListener { 

    private GoogleMap mMap; 
    GoogleApiClient mGoogleApiClient; 
    Location mLastLocation; 
    Marker mCurrLocationMarker; 
    LocationRequest mLocationRequest; 
    PendingResult<LocationSettingsResult> result; 
    final static int REQUEST_LOCATION = 199; 


    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_maps); 

     if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { 
      checkLocationPermission(); 
     } 
     // Obtain the SupportMapFragment and get notified when the map is ready to be used. 
     SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager() 
       .findFragmentById(R.id.map); 
     mapFragment.getMapAsync(this); 
    } 



    @Override 
    public void onMapReady(GoogleMap googleMap) { 
     mMap = googleMap; 
     mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL); 

     //Initialize Google Play Services 
     if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { 
      if (ContextCompat.checkSelfPermission(this, 
        Manifest.permission.ACCESS_FINE_LOCATION) 
        == PackageManager.PERMISSION_GRANTED) { 
       buildGoogleApiClient(); 
       createLocationRequest(); 
       mMap.setMyLocationEnabled(true); 
      } 
     } 
     else { 
      buildGoogleApiClient(); 
      createLocationRequest(); 
      mMap.setMyLocationEnabled(true); 
     } 
    } 

    private void createLocationRequest() { 
     mLocationRequest = new LocationRequest(); 


     mLocationRequest.setInterval(10000); 


     mLocationRequest.setFastestInterval(10000); 

     mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY); 
    } 

    protected synchronized void buildGoogleApiClient() { 
     mGoogleApiClient = new GoogleApiClient.Builder(this) 
       .addConnectionCallbacks(this) 
       .addOnConnectionFailedListener(this) 
       .addApi(LocationServices.API) 
       .build(); 
     mGoogleApiClient.connect(); 
    } 

    @Override 
    public void onConnected(Bundle bundle) { 

     mLocationRequest = LocationRequest.create(); 
     mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY); 
     mLocationRequest.setInterval(30 * 1000); 
     mLocationRequest.setFastestInterval(5 * 1000); 

     LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder() 
       .addLocationRequest(mLocationRequest); 
     builder.setAlwaysShow(true); 

     result = LocationServices.SettingsApi.checkLocationSettings(mGoogleApiClient, builder.build()); 

     result.setResultCallback(new ResultCallback<LocationSettingsResult>() { 
      @Override 
      public void onResult(LocationSettingsResult result) { 
       final Status status = result.getStatus(); 
       switch (status.getStatusCode()) { 
        case LocationSettingsStatusCodes.SUCCESS: 


         break; 
        case LocationSettingsStatusCodes.RESOLUTION_REQUIRED: 

         try { 

          status.startResolutionForResult(
            MapsActivity.this, 
            REQUEST_LOCATION); 
         } catch (IntentSender.SendIntentException e) { 
         } 
         break; 
        case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE: 

         break; 
       } 
      } 
     }); 

    } 

    @Override 
    public void onActivityResult(int requestCode, int resultCode, Intent data) 
    { 
     Log.d("onActivityResult()", Integer.toString(resultCode)); 

     switch (requestCode) 
     { 
      case REQUEST_LOCATION: 
       switch (resultCode) 
       { 
        case Activity.RESULT_OK: 
        { 
         Toast.makeText(MapsActivity.this, "Location enabled by user!", Toast.LENGTH_LONG).show(); 

         mMap.animateCamera(CameraUpdateFactory.zoomTo(11)); 
         break; 
        } 
        case Activity.RESULT_CANCELED: 
        { 
         Toast.makeText(MapsActivity.this, "Location not enabled, user cancelled.", Toast.LENGTH_LONG).show(); 
         break; 
        } 
        default: 
        { 
         break; 
        } 
       } 
       break; 
     } 
    } 

    @Override 
    public void onConnectionSuspended(int i) { 

    } 

    @Override 
    public void onLocationChanged(Location location) { 

     mLastLocation = location; 
     if (mCurrLocationMarker != null) { 
      mCurrLocationMarker.remove(); 
     } 

     LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude()); 
     MarkerOptions markerOptions = new MarkerOptions(); 
     markerOptions.position(latLng); 
     markerOptions.title("Current Position"); 
     markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA)); 
     mCurrLocationMarker = mMap.addMarker(markerOptions); 

     mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng)); 
     mMap.animateCamera(CameraUpdateFactory.zoomTo(11)); 

     if (mGoogleApiClient != null) { 
      LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this); 
     } 

    } 

    @Override 
    public void onConnectionFailed(ConnectionResult connectionResult) { 

    } 

    public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99; 
    public boolean checkLocationPermission(){ 
     if (ContextCompat.checkSelfPermission(this, 
       Manifest.permission.ACCESS_FINE_LOCATION) 
       != PackageManager.PERMISSION_GRANTED) { 

      if (ActivityCompat.shouldShowRequestPermissionRationale(this, 
        Manifest.permission.ACCESS_FINE_LOCATION)) { 


       ActivityCompat.requestPermissions(this, 
         new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 
         MY_PERMISSIONS_REQUEST_LOCATION); 


      } else { 
       ActivityCompat.requestPermissions(this, 
         new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 
         MY_PERMISSIONS_REQUEST_LOCATION); 
      } 
      return false; 
     } else { 
      return true; 
     } 
    } 

    @Override 
    public void onRequestPermissionsResult(int requestCode, 
              String permissions[], int[] grantResults) { 
     switch (requestCode) { 
      case MY_PERMISSIONS_REQUEST_LOCATION: { 
       if (grantResults.length > 0 
         && grantResults[0] == PackageManager.PERMISSION_GRANTED) { 

        if (ContextCompat.checkSelfPermission(this, 
          Manifest.permission.ACCESS_FINE_LOCATION) 
          == PackageManager.PERMISSION_GRANTED) { 

         if (mGoogleApiClient == null) { 
          buildGoogleApiClient(); 
         } 
         mMap.setMyLocationEnabled(true); 
        } 

       } else { 

        Toast.makeText(this, "permission denied", Toast.LENGTH_LONG).show(); 
       } 
       return; 
      } 

     } 
    } 
} 
+0

Monsieur, votre code fonctionne très bien. Mais je veux juste l'emplacement actuel, sans utiliser google maps. J'ai besoin de la valeur de la latitude et de la longitude. –

0

NE PAS UTILISER GPSTRACKER. Ce code est totalement cassé. Son connu pour être cassé pendant des années. Cela fonctionnera parfois, mais il a des défauts de conception qui le rendent non-modifiable. Particulièrement, il ne tient pas compte de la différence entre un fournisseur activé et un correctif d'emplacement, et s'appuie sur getlastKnownLocation qui ne devrait jamais être utilisé.

J'ai écrit un article sur ce blog il y a plusieurs années, en disant pourquoi il était cassé, et en fournissant une meilleure solution. Jetez GPTracker et utilisez-le, ou trouvez une autre solution. Mais le code que vous avez est inutilisable sans faire beaucoup d'études sur le fonctionnement de l'emplacement.

+0

Monsieur, j'ai essayé le code que vous avez donné dans votre blog, mais il donne null dans Location. –