2016-05-11 5 views
0

Ich arbeite an einem Projekt, wo ich auf den GPS-Standort des Benutzers zugreifen muss. Aufgrund von Android 6 benötige ich Laufzeitberechtigungen. Ich habe versucht, es zu tun, zum ersten Mal fragte es nach GPS-Standort auf Aktivität beginnt, aber ohne mir den Standort zu geben. Ich bekomme immer noch keine Standortkoordinaten. Hoffe jemand kann helfen?Laufzeit Berechtigung nicht arbeiten Zugang Fine Location Marshmallow

public class benzinpriser_akt extends AppCompatActivity implements OnItemClickListener { 


    public static final int MY_PERMISSION_REQUEST_GPS_LOCATION = 1 ; 
    LocationManager locationManager; 
    LocationListener locationListener; 
    Location currentLocation;  

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 

    locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE); 
    locationListener = new LocationListener() { 
     public void onLocationChanged(Location location) { 
      // Called when a new location is found by the network location provider. 
      currentLocation = location; 
      System.out.println("Current Location "+ currentLocation); 
     } 

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

     public void onProviderEnabled(String provider) { 
     } 

     public void onProviderDisabled(String provider) { 
     } 
    }; 

    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { 
     if (ActivityCompat.shouldShowRequestPermissionRationale(this, 
       Manifest.permission.ACCESS_FINE_LOCATION)) { 



     } else { 


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

    // Some other code regarding listview and fetching data from database 
} 



@Override 
public void onRequestPermissionsResult(int requestCode, 
             String permissions[], int[] grantResults) { 
    switch (requestCode) { 
     case MY_PERMISSION_REQUEST_GPS_LOCATION: { 
      // 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. 
       System.out.println("Permission Granted"); 
       locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener); 


      } else { 

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

     // other 'case' lines to check for other 
     // permissions this app might request 
    } 
} 
+0

Sie scheinen nicht den Fall zu behandeln, wo Sie bereits die Erlaubnis haben. – Michael

+0

Können Sie mich wissen, in welchem ​​Teil des Codes kann ich damit umgehen –

Antwort

0

Zu allererst hinzufügen theese zwei Zeilen zu Ihrer build.gradle:

public class benzinpriser_akt extends AppCompatActivity implements GoogleApiClient.ConnectionCallbacks, 
GoogleApiClient.OnConnectionFailedListener,LocationListener, android.location.LocationListener { 
private GoogleApiClient mGoogleApiClient; 
private LocationRequest mLocationRequest; 
private int UPDATE_INTERVAL = 20000; // 20 sec 
private int FASTEST_INTERVAL = 10000; // 10 sec 
private int DISPLACEMENT = 50; // get location per 50 meter change 
protected final String TAG = "Location Service"; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
super.onCreate(savedInstanceState); 
setContentView(yourlayout); 
//build google api client 
buildGoogleApiClient(); 

    } //oncreate end 
    protected synchronized void buildGoogleApiClient() { 
    Log.v(TAG, "google client building"); 
    if (GooglePlayServicesUtil.isGooglePlayServicesAvailable(this) == ConnectionResult.SUCCESS) { 

     mGoogleApiClient = new GoogleApiClient.Builder(thisService) 
       .addConnectionCallbacks(this) 
       .addOnConnectionFailedListener(this) 
       .addApi(LocationServices.API).build(); 
     if (!mGoogleApiClient.isConnected() || !mGoogleApiClient.isConnecting()) { 
      mGoogleApiClient.connect(); 
     } 

      startListenLocation(); 

    } else { 
     Log.e(TAG, "unable to connect to google play services."); 
    } 



} 

    public void createLocationRequestWithDialog(final Activity activity){ 

    mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY); 
    mLocationRequest.setInterval(UPDATE_INTERVAL); 
    mLocationRequest.setFastestInterval(FASTEST_INTERVAL); 
    LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder() 
      .addLocationRequest(mLocationRequest); 

    //************************** 
    builder.setAlwaysShow(true); //this is the key ingredient 
    //************************** 
    PendingResult<LocationSettingsResult> result = 
      LocationServices.SettingsApi.checkLocationSettings(mGoogleApiClient, builder.build()); 
    result.setResultCallback(new ResultCallback<LocationSettingsResult>() { 
     @Override 
     public void onResult(LocationSettingsResult result) { 
      final Status status = result.getStatus(); 
      final LocationSettingsStates state = result.getLocationSettingsStates(); 
      switch (status.getStatusCode()) { 
       case LocationSettingsStatusCodes.SUCCESS: 
        // All location settings are satisfied. The client can initialize location 
        // requests here. 
        break; 
       case LocationSettingsStatusCodes.RESOLUTION_REQUIRED: 
        // Location settings are not satisfied. But could be fixed by showing the user 
        // a dialog. 
        try { 
         // Show the dialog by calling startResolutionForResult(), 
         // and check the result in onActivityResult(). 
         status.startResolutionForResult(
           activity, 1000); 
        } catch (IntentSender.SendIntentException e) { 
         // Ignore the error. 
        } 
        break; 
       case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE: 
        // Location settings are not satisfied. However, we have no way to fix the 
        // settings so we won't show the dialog. 
        break; 
      } 
     } 
    }); 


} 

public void checkGpsPermission(Activity activity) { 
    if (ContextCompat.checkSelfPermission(activity, Manifest.permission.ACCESS_FINE_LOCATION) 
      != PackageManager.PERMISSION_GRANTED) { 
     ActivityCompat.requestPermissions(activity, 
       new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 
       PERMISSION_ACCESS_GPS); 

    } 
    else 
    { 
     createLocationRequestWithDialog(activity); 
    } 


} 

    protected void startListenLocation() { 
    if (ActivityCompat.checkSelfPermission(thisService, Manifest.permission.ACCESS_FINE_LOCATION) 
      != PackageManager.PERMISSION_GRANTED) { 
     //no permission , create a notification and want permission 
     NotificationManager notificationManager = (NotificationManager) 
       getSystemService(NOTIFICATION_SERVICE); 
     Notification n = new Notification.Builder(thisService) 
       .setContentTitle(" notification") 
       .setContentText("there is no permission about using gps services, please give location permissions") 
       .setSmallIcon(R.drawable.logo) 
       .setAutoCancel(true) 
       .build(); 
     notificationManager.notify((int)System.currentTimeMillis(), n); 
    } else { 
     // permission has been granted, continue as usual 

    if(mGoogleApiClient.isConnected()) { 
     LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this); 

    } 

    } 


} 

@Override 
public void onConnected(@Nullable Bundle bundle) { 

    if (mGoogleApiClient.isConnected() && mLastLocation != null) { 
     createLocationRequestWithDialog(); 
     startListenLocation(); 
    } 
} 
@Override 
public void onConnectionSuspended(int i) { 
    mGoogleApiClient.connect(); 
} 
//TODO add other override methods , onresume, onproviderenabled etc... 

}//class end 

Batterieverbrauch:

compile 'com.google.android.gms:play-services-maps:8.4.0' 
compile 'com.google.android.gms:play-services-location:8.4.0' 

Dann in Ihrer Tätigkeit Sie wie das umsetzen müssen

/* 
    Priority    update interval  Battery drain per hour (%)  Accuracy 
    HIGH_ACCURACY   5 seconds     7.25%     ~10 meters 
    BALANCED_POWER   20 seconds     0.6%     ~40 meters 
    NO_POWER    N/A       small     ~1 mile 

*/

+0

Ich habe es versucht, funktioniert –

+0

immer noch nicht funktioniert –

+0

Der Code senden Sie mir vor, gibt mehr Fehler können Sie den gleichen Code in meiner Klasse oben verwenden. Ich brauche GPS-Standort aufgrund von Projektanforderungen, aber thx für Beratung –

Verwandte Themen