2017-07-18 5 views
0

Permettez-moi de commencer en reconnaissant qu'il existe de nombreux résultats lorsque vous recherchez cette question particulière. Pourtant, rien de ce que j'ai essayé, selon ces réponses, fonctionne. Parfois, je reçois l'emplacement, parfois non. Si je joue avec le Location activer/désactiver je reçois toujours null en appelant getLastKnownLocation. Si parfois je révoque manuellement l'autorisation Location et que je l'active à nouveau, cela fonctionne. J'ai essayé de changer le LocationManager en location = locationManager .getLastKnownLocation(LocationManager.PASSIVE_PROVIDER); mais cela ne fonctionne pas.getLastKnownLocation renvoie parfois la valeur null

En fait, je fais ce qui suit:

public class GPSTracker implements LocationListener { 

    public static final int LOCATION_SETTINGS_REQUEST_CODE = 109; 

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

    private static boolean isGpsStatusChanged = false; 
    private static AlertDialog.Builder alertDialog; 

    private LocationManager locationManager; 
    private boolean canGetLocation = false; 
    private Location location; 
    private double latitude; 
    private double longitude; 
    private NewLocationListener newLocationListener; 

    public interface NewLocationListener { 
     void onLocationChanges(Location location); 
    } 

    public GPSTracker() { 

    } 

    @SuppressWarnings("all") 
    public Location getLocation() { 
     try { 
      locationManager = (LocationManager) BaseApplication.getContext().getSystemService(Context.LOCATION_SERVICE); 

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

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

      if (!isGPSEnabled && !isNetworkEnabled) { 
       // no network provider is enabled 
      } else { 
       this.canGetLocation = true; 
       // First get location from Network Provider 
       if (isNetworkEnabled) { 
        locationManager.requestLocationUpdates(
          LocationManager.NETWORK_PROVIDER, 
          MIN_TIME_BW_UPDATES, 
          MIN_DISTANCE_CHANGE_FOR_UPDATES, this); 
        Log.d("GPSTracker", "Network"); 
        if (locationManager != null) { 
         Log.d("GPSTracker", "Network - location manager != null"); 
         location = locationManager 
           .getLastKnownLocation(LocationManager.NETWORK_PROVIDER); 
         if (location != null) { 
          Log.d("GPSTracker", "Network - last known location != null"); 
          latitude = location.getLatitude(); 
          longitude = location.getLongitude(); 
          newLocationListener.onLocationChanges(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("GPSTracker", "GPS Enabled"); 
         if (locationManager != null) { 
          location = locationManager 
            .getLastKnownLocation(LocationManager.GPS_PROVIDER); 
          Log.d("LastKnownLocation", "Location: " + locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER)); 
          if (location != null) { 
           latitude = location.getLatitude(); 
           longitude = location.getLongitude(); 
           newLocationListener.onLocationChanges(location); 
          } 
         } 
        } 
       } 
      } 
     } catch (Exception e) { 
      Log.e(Constants.TAG, e.getMessage(), e); 
     } 

     return location; 
    } 

    public static boolean isGpsEnabled() { 
     LocationManager locationManager = (LocationManager) BaseApplication.getContext().getSystemService(Context 
       .LOCATION_SERVICE); 
     return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER); 
    } 

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

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

     // return latitude 
     return latitude; 
    } 

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

     // return longitude 
     return longitude; 
    } 

    public boolean canGetLocation() { 
     return this.canGetLocation; 
    } 

    public void setNewLocationListener(NewLocationListener newLocationListener) { 
     this.newLocationListener = newLocationListener; 
    } 

    public void removeLocationListener() { 
     this.newLocationListener = null; 
    } 

    @SuppressWarnings("InlinedApi") 
    public void showSettingsAlert(final Context context) { 
     if (alertDialog != null) { 
      return; 
     } 

     if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { 
      alertDialog = new AlertDialog.Builder(context, android.R.style.Theme_Material_Light_Dialog_Alert); 
     } else { 
      alertDialog = new AlertDialog.Builder(context); 
     } 
     alertDialog.setTitle(R.string.gps_window_title); 
     alertDialog.setMessage(R.string.gps_window_message); 

     alertDialog.setPositiveButton(R.string.gps_window_button_positive, new DialogInterface.OnClickListener() { 
      public void onClick(DialogInterface dialog, int which) { 
       Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS); 
       ((Activity) context).startActivityForResult(intent, LOCATION_SETTINGS_REQUEST_CODE); 
      } 
     }); 

     alertDialog.setNegativeButton(R.string.gps_window_button_negative, new DialogInterface.OnClickListener() { 
      public void onClick(DialogInterface dialog, int which) { 
       dialog.cancel(); 
      } 
     }); 

     alertDialog.show().setOnDismissListener(new DialogInterface.OnDismissListener() { 
      @Override 
      public void onDismiss(DialogInterface dialog) { 
       alertDialog = null; 
      } 
     }); 
    } 

    @Override 
    public void onLocationChanged(Location location) { 
     if (newLocationListener != null) { 
      newLocationListener.onLocationChanges(location); 
     } 
    } 

    @Override 
    public void onProviderDisabled(String provider) { 
    } 

    @Override 
    public void onProviderEnabled(String provider) { 
    } 

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

    public static boolean isGpsStatusChanged() { 
     return isGpsStatusChanged; 
    } 

    public static void setIsGpsStatusChanged(boolean isGpsStatusChanged) { 
     GPSTracker.isGpsStatusChanged = isGpsStatusChanged; 
    } 
} 

Et puis dans mon fragment:

private void statGPSLocationTracking() { 

    Log.d(Constants.TAG, "start gps update"); 
    // check if GPS enabled 
    gpsTracker = new GPSTracker(); 
    gpsTracker.setNewLocationListener(newLocationListener); 
    gpsTracker.getLocation(); 

    if (!gpsTracker.canGetLocation()) { 
     Log.d(Constants.TAG, "GPS not enabled, show enable dialog"); 
     // stop the gps tracker(removes the location update listeners) 
     gpsTracker.stopUsingGPS(); 

     // ask user to enable location 
     gpsTracker.showSettingsAlert(getActivity()); 
    } 
} 

private GPSTracker.NewLocationListener newLocationListener = new GPSTracker.NewLocationListener() { 
    @Override 
    public void onLocationChanges(Location loc) { 
     if (getActivity() == null) { 
      return; 
     } 
     // GPS location determined, load the web page and pass the coordinates in the header location section 
     Log.d(Constants.TAG, "Location listener onLocationChanges: " + loc); 
     infoManager.setCurrentLocation(loc); 
     checkRadioInfoNeeded(); 

     // stop the gps tracker(removes the location update listeners) 
     gpsTracker.stopUsingGPS(); 
    } 
}; 
+0

Copie possible de [Quelle est la fiabilité de getLastKnownLocation de LocationManager et à quelle fréquence est-il mis à jour?] (Https://stackoverflow.com/questions/7423624/how-reliable-is-locationmanagers-getlastknownlocation-and-how-often-is -it-updat) – j4rey89

Répondre

0

Cocher cette

public Location getLocation(){ 
     try{ 

      LocationManager locationManager = (LocationManager) mContext 
        .getSystemService(LOCATION_SERVICE); 

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

      // getting network status 
      boolean isNetworkEnabled = locationManager 
        .isProviderEnabled(LocationManager.NETWORK_PROVIDER); 
      if(!isGPSEnabled && !isNetworkEnabled){ 

      }else { 
       this.canGetLocation = true; 
       // First get location from Network Provider 
       if (isNetworkEnabled) { 
        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(); 
         } 
        } 
       } 
      } 

      // 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("GPS Enabled", "GPS Enabled"); 
        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; 

    } 
+0

Il est toujours 'null'. – JackW5808

+0

Est-ce que la permission de localisation est donnée dans l'appareil? –

+0

Et assurez-vous également que votre appareil stocke un dernier emplacement connu. Sinon, allez sur Google Maps et localisez ma position avec GPS. –

0

Sans cet endroit la permission android.Manifest.permission.ACCESS_FINE_LOCATION le getLastKnownLocation() sera toujours retourne null.

getLastKnownLocation() ne retourne pas l'emplacement immédiatement, il prend un certain temps.

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

cela

private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 0; 
private static final long MIN_TIME_BW_UPDATES = 5 * 1000; 

Retirez également votre code qui obtient l'emplacement du réseau. Accédez à Google Maps et vérifiez si les cartes sont en mesure de détecter votre position actuelle. Si votre carte est en mesure d'obtenir l'emplacement, votre code devrait également obtenir des points d'arrêt d'emplacement et voir où le vrai problème est.

+0

Je l'ai essayé et cela ne fonctionne toujours pas. J'arrive ici 'if (locationManager! = Null) { location = locationManager .getLastKnownLocation (LocationManager.PASSIVE_PROVIDER);' et le 'location' est' null'. – JackW5808

+0

@ JackW5808 Pourriez-vous essayer le même code dans un autre appareil et nous faire connaître le résultat? 2. Aussi pourriez-vous nous faire connaître le nom de votre appareil? –

+0

J'ai essayé à la fois l'émulateur Nexus 5X et Huawei P8. Je vais tester sur un autre appareil maintenant. – JackW5808