运行时权限不工作访问精确位置棉花糖

时间:2016-05-11 19:15:00

标签: android android-6.0-marshmallow android-permissions

我正在处理我需要访问用户的gps位置的项目。由于android 6,我需要运行时权限。我试图这样做,第一次在活动开始时询问gps位置,但没有给我位置。我仍然没有得到任何位置坐标。希望有人可以帮忙吗?

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

1 个答案:

答案 0 :(得分:0)

首先将两条线添加到build.gradle

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

然后在你的活动中你必须这样实现:

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 
  

电池耗尽:

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

* /