【问题标题】:How to grant ACCESS_FINE_LOCATION permission in Lollipop?如何在 Lollipop 中授予 ACCESS_FINE_LOCATION 权限?
【发布时间】:2016-12-02 05:48:14
【问题描述】:

我正在使用以下代码检查并请求 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 的权限?

【问题讨论】:

标签: android permissions gps


【解决方案1】:
ActivityCompat.requestPermissions(this, new String[]{
                Manifest.permission.ACCESS_FINE_LOCATION }, 1);

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

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

【讨论】:

    【解决方案2】:

    在清单中添加这些行:

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

    【讨论】:

      【解决方案3】:

      您可以使用以下代码。使用下面的代码,它会要求打开 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 &lt;= 21 gps 权限将被自动授予(如果您已在清单上定义权限),对于棉花糖及以上您需要请求运行时权限(也在清单中添加权限)但在permission granted 之后打开 GPS你可以使用上面的代码。

      使用此代码会出现一个警报框并要求打开 GPS(如果未激活)。所以你可以直接用上面的代码打开GPS。

      希望对您有所帮助。

      干杯!!

      【讨论】:

      • 如果问题重复,请将它们标记为 重复
      • write code for the requestpermission?如果您要给出答案,请给出完整的答案,以帮助 OP 和未来的读者继续获得完整和准确的答案
      猜你喜欢
      • 2011-10-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-09-28
      相关资源
      最近更新 更多