如何在Lollipop中授予ACCESS_FINE_LOCATION权限?

时间:2016-12-02 05:48:14

标签: android permissions gps

我正在使用以下代码检查并请求GPS权限:

if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
            != PackageManager.PERMISSION_GRANTED) {

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

我在清单中有以下内容:

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

我正在使用Android Studio将该应用部署到Android 5.0.2平板电脑。

我知道checkSelfPermission没有返回PERMISSION_GRANTED并执行requestPermissions,但它没有显示对话框或授予权限。如何授予应用程序使用GPS的权限?

3 个答案:

答案 0 :(得分:1)

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

此代码在android 6上请求运行时权限。对于较低版本,我启动设置意图,以便用户打开下面的首选设置(代替上面的代码)

Intent myIntent = new Intent(Settings.ACTION_SETTINGS);
                        startActivity(myIntent);

答案 1 :(得分:1)

在清单中添加以下行:

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

以及这些:

<!-- Below permissions are used to detect required hardware or service providers for the application -->
    <uses-feature
        android:name="android.hardware.location"
        android:required="true" />
    <uses-feature
        android:name="android.hardware.location.gps"
        android:required="true" />

答案 2 :(得分:0)

您可以使用以下代码。使用以下代码,它将要求打开GPS。

public class Activity extends AppCompatActivity implements GoogleApiClient.ConnectionCallbacks,
        GoogleApiClient.OnConnectionFailedListener, LocationListener {


    private final static int PLAY_SERVICES_RESOLUTION_REQUEST = 1000;

    private Location mLastLocation;

    // Google client to interact with Google API
    private GoogleApiClient mGoogleApiClient;

    // boolean flag to toggle periodic location updates
    private boolean mRequestingLocationUpdates = false;

    private LocationRequest mLocationRequest;

    // Location updates intervals in sec
    private static int UPDATE_INTERVAL = 600000; // 10 min
    private static int FATEST_INTERVAL = 600000; // 10 min
    private static int DISPLACEMENT = 5; // 5 meters

    PendingResult<LocationSettingsResult> result;

    AlertDialog.Builder alertDialogBuilder;
    LinearLayout parent;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);


        alertDialogBuilder = new AlertDialog.Builder(Activity.this);

        parent = new LinearLayout(ActivitySetting.this);
        parent.setGravity(Gravity.CENTER);
        parent.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT));


        alertDialogBuilder.setTitle("name");

        // First we need to check availability of play services
        if (checkPlayServices()) {

            // Building the GoogleApi client
            buildGoogleApiClient();

            createLocationRequest();
        }

        LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
                .addLocationRequest(mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY));


        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 locationSettingsStates = result.getLocationSettingsStates();
                // final LocationSettingsStates locationSettingsStates = result.getLocationSettingsStates();
                switch (status.getStatusCode()) {
                    case LocationSettingsStatusCodes.SUCCESS:

                        break;
                    case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:

                        alertDialogBuilder.setMessage("Turn On GPS");
                        alertDialogBuilder.setView(parent);
                        alertDialogBuilder.setCancelable(false);

                        alertDialogBuilder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                try {
                                    // Show the dialog by calling startResolutionForResult(),
                                    // and check the result in onActivityResult().
                                    status.startResolutionForResult(ActivitySetting.this, 1000);
                                } catch (IntentSender.SendIntentException e) {
                                    // check  error.
                                }

                            }
                        });

                        alertDialogBuilder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                try {
                                    // Show the dialog by calling startResolutionForResult(),
                                    finish();
                                } catch (Exception e) {
                                    // check error.
                                }

                            }
                        });
                        alertDialogBuilder.create();
                        alertDialogBuilder.show();
                        break;
                    case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:

                        // you can do here what ever you want.

                        break;
                }
            }
        });

    }

    @Override
    protected void onStart() {
        super.onStart();
        if (mGoogleApiClient != null) {
            mGoogleApiClient.connect();
        }
    }


    @Override
    protected void onResume() {
        super.onResume();

        checkPlayServices();

        // Resuming the periodic location updates
        if (mGoogleApiClient.isConnected() && mRequestingLocationUpdates) {
            startLocationUpdates();
        }
    }

    /**
     * Creating google api client object
     */
    protected synchronized void buildGoogleApiClient() {
        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API).build();
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        //final LocationSettingsStates states = LocationSettingsStates.fromIntent(data);
        switch (requestCode) {
            case 1000:
                switch (resultCode) {
                    case Activity.RESULT_OK:

                        // If user has active gps you will get it here

                        break;
                    case Activity.RESULT_CANCELED:
                        // The user was asked to change settings, but chose not to turn on

                        break;
                    default:

                        break;
                }
                break;
        }
    }

    /**
     * Method to verify google play services on the device
     */
    private boolean checkPlayServices() {
        int resultCode = GooglePlayServicesUtil
                .isGooglePlayServicesAvailable(this);
        if (resultCode != ConnectionResult.SUCCESS) {
            if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) {
                GooglePlayServicesUtil.getErrorDialog(resultCode, this,
                        PLAY_SERVICES_RESOLUTION_REQUEST).show();
            } else {
                Toast.makeText(getApplicationContext(),
                        "This device is not supported.", Toast.LENGTH_LONG)
                        .show();
                finish();
            }
            return false;
        }
        return true;
    }


    /**
     * Google api callback methods
     */
    @Override
    public void onConnectionFailed(ConnectionResult result) {
        Log.i("fsAil", "Connection failed: ConnectionResult.getErrorCode() = "
                + result.getErrorCode());
    }

    @Override
    public void onConnected(Bundle arg0) {

    }

    @Override
    public void onConnectionSuspended(int arg0) {
        mGoogleApiClient.connect();
    }

    @Override
    public void onLocationChanged(Location location) {


    }

}

此处API <= 21 gps权限将自动授予(如果您已对清单定义了权限),对于marshmallow及以上版本,您需要请求运行时权限(还要在清单中添加权限),但要在{{之后}启用GPS {1}}您可以使用上述代码。

使用此代码会出现一个警告框并要求打开GPS(如果未激活)。因此,您可以使用上述代码直接打开GPS。

希望这对你有所帮助。

干杯!!