3

Ich leide an dem Problem, Wert 0.0 als Breiten- und Längengrad in Android Marshmallow (API 23) zu erhalten, d. H. 6.0.Latitude und Longitude 0.0 in Android erhalten M

Ich habe viel darüber gesucht, aber keine Lösung gefunden. Mein Code ist voll funktionsfähig für die anderen API-Versionen, die weniger als 23 sind.

Ich habe auch den Code für SelfPermission und die alle arbeiten stattdessen gibt es mir 0.0 so spät und lang.

haben Sie einen Blick auf die Art, wie ich bin folgende:

GPSTracker.java

public class GPSTracker extends Service implements LocationListener { 

    private 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 

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

    // 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; 

    Activity activity; 

    public GPSTracker() { 
    } 

    public GPSTracker(Context context, Activity activity) { 
     this.mContext = context; 
     this.activity = activity; 
     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; 
       if (isNetworkEnabled) { 
        int requestPermissionsCode = 50; 
        if (ContextCompat.checkSelfPermission(activity, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(activity, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { 
         ActivityCompat.requestPermissions(activity, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, requestPermissionsCode); 

        } else { 
         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 latitude/longitude using GPS Services 
       if (isGPSEnabled) { 
        if (location == null) { 
         if (ContextCompat.checkSelfPermission(activity, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(activity, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { 
          ActivityCompat.requestPermissions(activity, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 50); 

         } else { 
          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) { 
      if (ContextCompat.checkSelfPermission(activity, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(activity, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { 
       ActivityCompat.requestPermissions(activity, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 50); 

      } else { 
       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/Wi-Fi enabled 
    * @return boolean 
    * */ 
    public boolean canGetLocation() { 
     return this.canGetLocation; 
    } 


    /** 
    * Function to show settings alert dialog. 
    * On pressing the Settings button it will launch 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 the 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 the 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; 
    } 
} 

DashboardActivity.java:

In onCreate() Ich habe GPSTracker initialisiert:

gps = new GPSTracker(mContext,DashboardActivity.this); 

     // Check if GPS enabled 
     if(gps.canGetLocation()) { 

      double latitude = gps.getLatitude(); 
      double longitude = gps.getLongitude(); 

      // \n is for new line 
      Toast.makeText(getApplicationContext(), "Your Location is - \nLat: " + latitude + "\nLong: " + longitude, Toast.LENGTH_LONG).show(); 
     } else { 
      // Can't get location. 
      // GPS or network is not enabled. 
      // Ask user to enable GPS/network in settings. 
      gps.showSettingsAlert(); 
     } 

AndroidManifest.xml

<permission android:name="android.permission.ACCESS_COARSE_LOCATION" /> 
    <permission android:name="android.permission.ACCESS_FINE_LOCATION" /> 


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

Ich habe viele Links in Stack Overflow, aber keiner von ihnen hat mir geholfen, dieses Problem zu lösen.

Ich würde jede Art von Hilfe hier schätzen.

+0

gewähren Ihnen die Erlaubnis Speicherort zugreifen App? –

+0

@ VivekMishra: Ja, ich habe für beide die Erlaubnis erteilt. – KishuDroid

+0

@VivekMishra: Ja, ich habe dir dafür geantwortet – KishuDroid

Antwort

14

Mit Hilfe von CommonsWare und Blackkara Antwort konnte ich mein Problem lösen.

Gemäß ihrem Vorschlag habe ich meinen Code geändert und habe nach jedem einzelnen Schritt meines Codes mit Debugging.

Deshalb kam ich mit dem Problem, dass meine onLocationChanged() nicht im Fall von Marshmallow gefeuert wurde, aber überraschend, es wird Feuer im Fall von älteren Geräten, die weniger als Android M oder 6.0 sind.

Für diese Lösung Ich habe meinen Code wie unten verändert, hier ich den vollständigen Code bin Entsendung so dass jeder, der das gleiche Problem hat, kann es loswerden.

GPSTracker.java

public class GPSTracker extends Service{ 

    private 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 

    // The minimum distance to change Updates in meters 
    private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 1000; // 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; 

    Activity activity; 

    public GPSTracker() { 
    } 

    public GPSTracker(Context context, Activity activity) { 
     this.mContext = context; 
     this.activity = activity; 
     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; 
       if (isNetworkEnabled) { 
        int requestPermissionsCode = 50; 

        locationManager.requestLocationUpdates(
          LocationManager.NETWORK_PROVIDER, 
          MIN_TIME_BW_UPDATES, 
          MIN_DISTANCE_CHANGE_FOR_UPDATES, mLocationListener); 
        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 latitude/longitude using GPS Services 
      if (isGPSEnabled) { 
       if (location == null) { 
        if (ContextCompat.checkSelfPermission(activity, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(activity, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { 
         ActivityCompat.requestPermissions(activity, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 50); 

        } else { 
         locationManager.requestLocationUpdates(
           LocationManager.GPS_PROVIDER, 
           MIN_TIME_BW_UPDATES, 
           MIN_DISTANCE_CHANGE_FOR_UPDATES, mLocationListener); 
         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() { 

    } 


    private final LocationListener mLocationListener = new LocationListener() { 
     @Override 
     public void onLocationChanged(final Location location) { 

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

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

     } 

     @Override 
     public void onProviderEnabled(String provider) { 

     } 

     @Override 
     public void onProviderDisabled(String provider) { 

     } 
    }; 

    /** 
    * 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/Wi-Fi enabled 
    * @return boolean 
    * */ 
    public boolean canGetLocation() { 
     return this.canGetLocation; 
    } 


    /** 
    * Function to show settings alert dialog. 
    * On pressing the Settings button it will launch 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 the 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 the cancel button 
     alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { 
      public void onClick(DialogInterface dialog, int which) { 
       dialog.cancel(); 
      } 
     }); 

     // Showing Alert Message 
     alertDialog.show(); 
    } 


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

DashboardActivity.java

public class DashboardActivity extends Activity {  

    Context mContext; 

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

     mContext = this; 

     if (ContextCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { 
      ActivityCompat.requestPermissions(DashboardActivity.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1); 

     } else { 
      Toast.makeText(mContext,"You need have granted permission",Toast.LENGTH_SHORT).show(); 
      gps = new GPSTracker(mContext, DashboardActivity.this); 

      // Check if GPS enabled 
      if (gps.canGetLocation()) { 

       double latitude = gps.getLatitude(); 
       double longitude = gps.getLongitude(); 

       // \n is for new line 
       Toast.makeText(getApplicationContext(), "Your Location is - \nLat: " + latitude + "\nLong: " + longitude, Toast.LENGTH_LONG).show(); 
      } else { 
       // Can't get location. 
       // GPS or network is not enabled. 
       // Ask user to enable GPS/network in settings. 
       gps.showSettingsAlert(); 
      } 
     }   
    } 


    @Override 
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) { 
     super.onRequestPermissionsResult(requestCode, permissions, grantResults); 

     switch (requestCode) { 
      case 1: { 
       // If request is cancelled, the result arrays are empty. 
       if (grantResults.length > 0 
         && grantResults[0] == PackageManager.PERMISSION_GRANTED) { 

        // permission was granted, yay! Do the 

        // contacts-related task you need to do. 

        gps = new GPSTracker(mContext, DashboardActivity.this); 

        // Check if GPS enabled 
        if (gps.canGetLocation()) { 

         double latitude = gps.getLatitude(); 
         double longitude = gps.getLongitude(); 

         // \n is for new line 
         Toast.makeText(getApplicationContext(), "Your Location is - \nLat: " + latitude + "\nLong: " + longitude, Toast.LENGTH_LONG).show(); 
        } else { 
         // Can't get location. 
         // GPS or network is not enabled. 
         // Ask user to enable GPS/network in settings. 
         gps.showSettingsAlert(); 
        } 

       } else { 

        // permission denied, boo! Disable the 
        // functionality that depends on this permission. 

        Toast.makeText(mContext, "You need to grant permission", Toast.LENGTH_SHORT).show(); 
       } 
       return; 
      } 
     } 
    } 
} 

Manifest.xml:

Permission die

012 hinzugefügt werden,
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /> 
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> 
    <uses-permission android:name="android.permission.INTERNET" /> 

Declare Dienst in Anwendungs ​​Tag:

<service android:name=".utilities.GPSTracker"/> 
+1

Vielen Dank für Ihre Arbeit .First Zeit ** lat, long ** zeigt '0.0' dann in Ordnung –

+0

Danke für mein Leben zu retten .... –

+1

ich Ihren Code implementiert haben, aber immer noch 0,0 in Eibisch bekommen. – Sidhartha

1

Zuerst entfernen Sie diese:

<permission android:name="android.permission.ACCESS_COARSE_LOCATION" /> 
<permission android:name="android.permission.ACCESS_FINE_LOCATION" /> 

Diese werden von der Plattform definiert, nicht Sie.

Sie reagieren auch nicht, wenn der Benutzer Ihnen tatsächlich die Erlaubnis erteilt. Fordern Sie die Berechtigungen in Ihrer Aktivität an, und erstellen Sie keine Instanz von GPSTracker, bis Sie die Berechtigung haben. Das kann sofort sein, wenn checkSelfPermission() sagt, dass Sie die Erlaubnis haben. Andernfalls wird das sein, wenn die Aktivität mit onRequestPermissionResult() aufgerufen wird.

Die Lage Arbeit selbst ist auch fehlerhaft, in dem Sie scheinen zu denken, dass Sie sofort eine Position bekommen, die nicht der Fall der Zeit sein wird.

+0

Lassen Sie mich versuchen, was Sie vorgeschlagen haben. – KishuDroid

+0

Noch bekomme ich 0.0 als Längen- und Breitengrad. Ich habe meinen Code geändert, wie Sie vorgeschlagen, aber immer noch nicht :-( – KishuDroid

1

Sie könnten unten Ursachen haben?

Erste Ursache

Location-Anbieter gibt Ihnen nicht 0.0 Werte wie Breite und Länge. Sie bekommen, was Sie zum ersten Mal definiert haben. Weil Sie keinen neuen Standort erhalten haben oder getLastKnownLocation() gibt null zurück. So Breiten- und Längen Variablen behalten ihre ersten Werte (0,0)

double latitude; 
double longitude; 

Zweite Ursache

Wann immer Sie getLocation() -Methode aufrufen, getLastKnownLocation() -Methode wird nichts, bis OnLocationChanged Feuer tun!(Je nach Anbieter)

@Override 
public void onLocationChanged(Location location) { 

} 

Erarbeitet für 'je nach Anbieter'

Sie sowohl GPS als auch Netzbetreiber angefordert.

requestLocationUpdates(LocationManager.NETWORK_PROVIDER ... mLocationListener); 
requestLocationUpdates(LocationManager.GPS_PROVIDER ... mLocationListener); 

Und dann hat genannt getLastKnownLocation Methode für beiden zwei Anbieter

locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER); 
locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER); 

werden angenommen, dass diese beiden Anbieter null zurückgekehrt. In diesem Fall müssen Sie warten, bis die onLocationChanged-Methode ausgelöst wurde. Andernfalls werden Sie von getLastKnownLocation Methode je nach Anbieter null bekommen

@Override 
public void onLocationChanged(final Location location) { 

    String providerName = location.getProvider(); 

    if(providerName.equals(LocationManager.GPS_PROVIDER)){ 
     // onLocationChanged method is fired by gps provider. 
     // After this point, getLastKnownLocation(); method returns not-null 
     // for LocationManager.GPS_PROVIDER 
    } 

    if(providerName.equals(LocationManager.NETWORK_PROVIDER)){ 
     // onLocationChanged method is fired by network provider. 
     // After this point, getLastKnownLocation(); method returns not-null 
     // for LocationManager.NETWORK_PROVIDER 
    } 
} 
+0

Je nach Provider, was es bedeutet? Können Sie es bitte eloborate? – KishuDroid

+0

Edited die Antwort. – Blackkara