2017-05-03 2 views
0

Ich brauche den aktuellen Gerätestandort (lat/lng), aber "getCurrentLocation()" zeigt die ganze Zeit "Kein Provider" an, daher ist der Standort null. Ich nenne diese Methode in onCreate() und erklärt alle Berechtigungen in Manifest-Datei:Aktuellen Standort kann nicht abgerufen werden

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

Standortdienste auf realen Gerät sind ebenfalls aktiviert.

GetCurrentLocation() Java-Code:

public void getCurrentLocation() { 
    locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE); 
    Criteria c = new Criteria(); 
    provider = locationManager.getBestProvider(c, false); 
    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. 
     return; 
    } 
    location = locationManager.getLastKnownLocation(provider); 
    if(location!=null) 
    { 
     double lng=location.getLongitude(); 
     double lat=location.getLatitude(); 
     Toast.makeText(this, Double.toString(lat) + "\n" + Double.toString(lng), Toast.LENGTH_SHORT).show(); 
    } 
    else 
    { 
     Toast.makeText(this, "No provider", Toast.LENGTH_SHORT).show(); 
    } 
} 

Wie kann ich es beheben?

P.S .: Ich habe viele ähnliche Fragen überarbeitet, kann aber keine passende Lösung finden.

+0

Sie haben den Teil über die Erlaubnis kommentiert, haben Sie zumindest die Erlaubnis gegeben, die Einstellungen zu verwenden? (Android 5.0 und älter) – AxelH

Antwort

0

Zuerst überlegen Sie, ob Sie FusedLocationProvider anstelle von LocationManager verwenden. Here können Sie einen Leitfaden zur Verwendung von ID finden.

Zweitens - Sie versuchen, "letzten bekannten Ort" zu bekommen, und es wäre nicht immer da. Um den Standort des Benutzers zu erhalten, müssen Sie Aktualisierungen für LocationManager abonnieren. This ist ein Beispiel, wie es geht.

+0

* Um den Standort des Benutzers zu empfangen, müssen Sie Aktualisierungen von LocationManager abonnieren *, die nicht zutreffen. Nur wenn Sie Updates wünschen –

+0

@TimCastelijns wenn Sie nicht Ort als letzte bekannt erhalten, dann ist das Abonnieren die einzige Option. – Ekalips

-2
public class GPSTracker extends Service implements LocationListener { 

private final Activity mContext; 

// flag for GPS status 
boolean isGPSEnabled = false; 

// flag for network status 
boolean isNetworkEnabled = false; 

// flag for GPS status 
boolean canGetLocation = false; 

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

public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99; 

// The minimum distance to change Updates in meters 
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters 

// The minimum time between updates in milliseconds 
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute 

// Declaring a Location Manager 
protected LocationManager locationManager; 
public GPSTracker(Activity context) { 
    this.mContext = context; 
    getLocation(); 
} 

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

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

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

     if (!isGPSEnabled && !isNetworkEnabled) { 
      // no network provider is enabled 
     } else { 
      this.canGetLocation = true; 
      // First get location from Network Provider 
      checkLocationPermission(); 
      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; 
} 

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

/** 
* 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("Please enable GPS to get locations."); 

    // 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) { 
} 

@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; 
} 

public boolean checkLocationPermission() 
{ 
    if (ContextCompat.checkSelfPermission(mContext, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) 
    { 
     // Should we show an explanation? 
     if (ActivityCompat.shouldShowRequestPermissionRationale(mContext, android.Manifest.permission.ACCESS_FINE_LOCATION)) 
     { 
      // Show an expanation to the user *asynchronously* -- don't block 
      // this thread waiting for the user's response! After the user 
      // sees the explanation, try again to request the permission. 

      //Prompt the user once explanation has been shown 
      ActivityCompat.requestPermissions(mContext, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION}, 
        MY_PERMISSIONS_REQUEST_LOCATION); 
     } 
     else 
     { 
      // No explanation needed, we can request the permission. 
      ActivityCompat.requestPermissions(mContext, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION}, 
        MY_PERMISSIONS_REQUEST_LOCATION); 
     } 
     return false; 
    } 
    else 
    { 
     if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) 
     { 
      showGPSDisabledAlertToUser(); 
     } 

     return true; 
    } 
} 

private void showGPSDisabledAlertToUser() 
{ 
    AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(mContext); 
    alertDialogBuilder.setMessage("GPS is disabled in your device. Would you like to enable it?") 
      .setCancelable(false) 
      .setPositiveButton("Settings", new DialogInterface.OnClickListener() { 
       public void onClick(DialogInterface dialog, int id) { 
        Intent callGPSSettingIntent = new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS); 
        mContext.startActivity(callGPSSettingIntent); 
       } 
      }); 
    alertDialogBuilder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() 
    { 
     public void onClick(DialogInterface dialog, int id) 
     { 
      dialog.cancel(); 
     } 
    }); 
    AlertDialog alert = alertDialogBuilder.create(); 
    alert.show(); 
} 

}

diesen Code Versuchen Sie, und wenn Sie die Lage bekommen benötigen einen GPS-Objekt erstellen und abrufen das lat und lange

zB:

GPSTracker gpsTracker = new GPSTracker(activity); 
      Latitude = gpsTracker.getLatitude(); 
      Longtude = gpsTracker.getLongitude(); 
+0

Wenn der 'Standort' aktualisiert würde? 'public void onLocationChanged (Location location) {' ist nicht implementiert. Ich denke nicht, dass dies die beste Lösung ist, um den Zuhörer dazu zu bringen, nur eine Position zu bekommen. – AxelH

+2

Kopieren Sie eine LKW-Ladung Code aus Ihrem eigenen Projekt einfügen keine gute Antwort. Dies beantwortet in keiner Weise die Frage –

+0

Ich benutze den exakt gleichen Code für den Breiten- und Längengrad –

0
provider = locationManager.getBestProvider(c, true); 

try Diese Änderung in Ihrem Code

0

Es ist nicht garantiert, dass .getLastKnownLocation() eine zuvor gespeicherte Standortdaten zurückgibt.

Es kann eine null zurückgeben.

Sie müssen also auf den Fall vorbereitet sein, in dem Sie auf Standortaktualisierungen warten müssen. Sie registrieren sich für sie wie folgt:

locationManager 
      .requestLocationUpdates(provider, 0, 0, 
        new LocationListener() { 
         @Override 
         public void onLocationChanged(Location location) { 
          //here you receive the new location 
         } 

         @Override 
         public void onStatusChanged(String s, int i, Bundle bundle) { 

         } 

         @Override 
         public void onProviderEnabled(String s) { 

         } 

         @Override 
         public void onProviderDisabled(String s) { 

         } 
        });); 
Verwandte Themen