1

Ich entwickle eine Anwendung, die GPS aktivieren und den aktuellen Standort abrufen. Mein Code funktioniert gut in allen Android-Version erwarten API 23, d. H. Marshmallows. Ich teste in Nexus 5 (API 23), Galaxy Note 3 (API 22).Wie bekomme ich den Standort (lat, lng) in API 23 und höher in Android programmatisch?

Hier ist mein Code

public void program() 
{ 
    locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); 
    locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, MINIMUM_TIME_BETWEEN_UPDATES, MINIMUM_DISTANCE_CHANGE_FOR_UPDATES, new MyLocationListener()); 

    if (!locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) { 

     AlertDialog.Builder builder = new AlertDialog.Builder(NearBy.this); 
     builder.setTitle("Location Service is Not Active"); 
     builder.setMessage("Please Enable your location services").setCancelable(false) 
       .setPositiveButton("OK", new DialogInterface.OnClickListener() { 
        public void onClick(DialogInterface dialog, int id) { 

         Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS); 
         startActivity(intent); 

        } 
       }); 
     AlertDialog alert = builder.create(); 
     alert.show(); 
    } else if (locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) { 
     Location location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER); 
     Geocoder geocoder = new Geocoder(this, Locale.getDefault()); 
     List<Address> addresses = null; 
     try { 
      addresses = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1); 

      final String cityName = addresses.get(0).getAddressLine(0) + " "; 
      String stateName = addresses.get(0).getAddressLine(1) + " "; 
      String countryName = addresses.get(0).getAddressLine(2) + " "; 
      String country = addresses.get(0).getCountryName() + " "; 
      String Area = addresses.get(0).getSubAdminArea() + " "; 
      String Area1 = addresses.get(0).getAdminArea() + " "; 
      String Area2 = addresses.get(0).getLocality() + " "; 
      String Area3 = addresses.get(0).getSubLocality(); 
      Log.e("Locaton", cityName + stateName + countryName + country + Area + Area1 + Area2 + Area3); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } catch (NullPointerException e) { 
      e.printStackTrace(); 
     } 
    } 
} 

Ich erhalte Nullpointer bei

  addresses = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1); 

nur in Nexus 5 (API 23). Ich habe auch die Erlaubnis (ACCESS_FINE_LOCATION und ACCESS_COARSE_LOCATION) sowohl im Mainfest als auch während der Laufzeit erteilt.

Bitte bieten Sie eine Lösung dafür.

AKTUALISIERT

ich meinen Code geändert haben. Ich habe eine GPSTracker Klasse und ich bin immer lat, Lng als 0

GPSTracker.java

public class GPSTracker extends Activity implements LocationListener { 
private final Context 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 

private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters 

private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute 

protected LocationManager locationManager; 

public GPSTracker(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 (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 (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; 
} 
@TargetApi(Build.VERSION_CODES.M) 
public void stopUsingGPS() { 
    if (locationManager != null) { 
     if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { 

      return; 
     } 
     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() { 
    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 currentLocation) { 

    this.location = currentLocation; 
    getLatitude(); 
    getLongitude(); 

} 

@Override 
public void onProviderDisabled(String provider) { 

} 

@Override 
public void onProviderEnabled(String provider) { 


} 

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

} 
} 
+0

Können Sie die Logcat-Ausgabe veröffentlichen? – cafebabe1991

+0

sollten Sie überprüfen Laufzeit Berechtigung wie If (Build.VERSION.SDK_INT> = 23 && ContextCompat.checkSelfPermission (context, android.Manifest.permission.ACCESS_FINE_LOCATION)! = PackageManager.PERMISSION_GRANTED && ContextCompat.checkSelfPermission (context, android.Manifest.permission.ACCESS_COARSE_LOCATION)! = PackageManager.PERMISSION_GRANTED) { return ; } – saeed

+0

GPSTracker.java arbeitete für mich PLZ zu bekommen - danke! – gnB

Antwort

2

Problem

The location obtained may be null if the last know location could not be found due to various reasons. Read about it in the docs [here][2] 

Grund/Wie ich es debuggt

  1. getFromLocation wirft keinen Nullpointer gemäß Dokumentation, daher ist das Problem in Ihrem Standortobjekt.

    Read here about this method

Abhilfe

Location location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER); 

Überprüfen Sie, ob die Lage in dem obigen Schritt NOT NULL erhalten wird, und dann mit dem Geocoder fortzufahren.

Code-Snippet

... 
else if (locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) { 
    Location location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER); 
    if(location == null) { 
     log.d("TAG", "The location could not be found"); 
     return; 
    } 
    //else, proceed with geocoding. 
    Geocoder geocoder = new Geocoder(this, Locale.getDefault()); 

den Standort Fetching - Ein Beispiel

Read here

komplette Code

View it here

+0

Wenn das Problem in meinem Standort ist, dann werde ich lat, lng mit dem gleichen Code in anderen Geräten, die in API 22 und darunter läuft. Eigentlich habe ich jetzt einen GPSTracker.java und ich bekomme lat und lng als 0 –

+0

@AnishKumar: Das ist nur in anderen Geräten möglich, wenn der lastKnownLocation in ihnen verfügbar war. Versuchen Sie, das Standortobjekt in diesen Geräten zu drucken, und Sie werden selbst sehen – cafebabe1991

+0

Fine @ cafebabe1991. Ich werde es Ihnen kurz mitteilen. –

0

Zuerst in Marshmallow alle Erlaubnis zur Laufzeit auch hinzufügen. Ansonsten Bitte starte dein Handy neu und überprüfe es erneut.